How can prepared statements be used effectively in PHP to avoid inefficient queries within loops?

When executing SQL queries within loops in PHP, it is important to use prepared statements to avoid inefficient queries. Prepared statements allow the database to compile the query once and execute it multiple times with different parameters, reducing the overhead of parsing and optimizing the query each time it is executed within the loop. Example PHP code snippet using prepared statements to avoid inefficient queries within loops:

// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

// Sample loop
foreach ($items as $item) {
    // Prepare a SQL statement
    $stmt = $pdo->prepare("SELECT * FROM items WHERE id = :id");

    // Bind parameters
    $stmt->bindParam(':id', $item['id']);

    // Execute the query
    $stmt->execute();

    // Fetch results
    $result = $stmt->fetch(PDO::FETCH_ASSOC);

    // Process the result
    // (e.g., print_r($result);)
}

// Close the database connection
$pdo = null;