How can the performance of a PHP script that processes a large number of SQL queries be optimized?

When processing a large number of SQL queries in a PHP script, the performance can be optimized by using prepared statements instead of regular queries. Prepared statements can be reused multiple times with different parameters, reducing the overhead of query parsing and execution. This can significantly improve the efficiency of the script.

// Connect to the database
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

// Prepare a statement
$stmt = $pdo->prepare("SELECT * FROM my_table WHERE id = :id");

// Bind parameters and execute the statement in a loop
foreach ($ids as $id) {
    $stmt->bindParam(':id', $id);
    $stmt->execute();
    
    // Process the results
    while ($row = $stmt->fetch()) {
        // Do something with the data
    }
    
    // Reset the statement for the next iteration
    $stmt->closeCursor();
}