What are some best practices for structuring SQL queries in PHP to efficiently retrieve and display images from a database in a gallery format?

When retrieving and displaying images from a database in a gallery format using SQL queries in PHP, it is important to use efficient techniques to minimize load times and optimize performance. One best practice is to retrieve only the necessary data for each image, such as the image URL and any relevant metadata, to reduce the amount of data transferred. Additionally, consider using pagination to limit the number of images displayed on each page, further improving load times.

<?php
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "gallery";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Retrieve images from the database
$sql = "SELECT image_url, description FROM images LIMIT 10"; // Limiting to 10 images for pagination
$result = $conn->query($sql);

// Display images in a gallery format
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo '<div class="image">';
        echo '<img src="' . $row["image_url"] . '" alt="' . $row["description"] . '">';
        echo '<p>' . $row["description"] . '</p>';
        echo '</div>';
    }
} else {
    echo "0 results";
}

// Close the database connection
$conn->close();
?>