How can PHP code be optimized to efficiently handle the display of image descriptions in a PHP news system?

When displaying image descriptions in a PHP news system, it is important to optimize the code to efficiently handle the task. One way to do this is by storing the image descriptions in a database table and retrieving them using a single query instead of querying the database for each image separately. This can help reduce the number of database queries and improve the performance of the system.

// Assuming $imageIds is an array of image IDs
// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=news_system', 'username', 'password');

// Prepare a single query to retrieve image descriptions for all image IDs
$stmt = $pdo->prepare("SELECT id, description FROM images WHERE id IN (" . implode(',', $imageIds) . ")");
$stmt->execute();

// Fetch all image descriptions and store them in an associative array
$imageDescriptions = [];
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $imageDescriptions[$row['id']] = $row['description'];
}

// Loop through the image IDs and display the image descriptions
foreach ($imageIds as $imageId) {
    echo "Image ID: $imageId - Description: " . $imageDescriptions[$imageId] . "<br>";
}