What are some best practices for efficiently counting and displaying the number of additional photos for each main photo in a PHP script?

When displaying multiple photos, it's important to efficiently count and display the number of additional photos for each main photo. One way to achieve this is by storing the total number of photos for each main photo in a database table and then querying this information when displaying the photos. This approach helps to minimize the number of database queries and ensures efficient counting and displaying of additional photos.

// Assuming you have a database table named 'photos' with columns 'id', 'main_photo_id', and 'photo_url'

// Query to get the main photos along with the count of additional photos
$query = "SELECT main_photo_id, COUNT(id) AS additional_photos_count 
          FROM photos 
          GROUP BY main_photo_id";

$result = mysqli_query($connection, $query);

if(mysqli_num_rows($result) > 0) {
    while($row = mysqli_fetch_assoc($result)) {
        $main_photo_id = $row['main_photo_id'];
        $additional_photos_count = $row['additional_photos_count'];
        
        // Display main photo and additional photos count
        echo "Main Photo ID: $main_photo_id, Additional Photos Count: $additional_photos_count <br>";
    }
}