How can the code provided be optimized for better performance, especially in terms of database queries and data retrieval?

The code can be optimized for better performance by reducing the number of database queries and optimizing the data retrieval process. One way to achieve this is by using a single query to fetch all the necessary data instead of making multiple queries for each item.

// Original code
$items = [];
foreach ($item_ids as $item_id) {
    $query = "SELECT * FROM items WHERE id = $item_id";
    $result = mysqli_query($connection, $query);
    $item = mysqli_fetch_assoc($result);
    $items[] = $item;
}

// Optimized code
$item_ids_str = implode(',', $item_ids);
$query = "SELECT * FROM items WHERE id IN ($item_ids_str)";
$result = mysqli_query($connection, $query);
$items = mysqli_fetch_all($result, MYSQLI_ASSOC);