How can prepared statements in PHP help optimize queries, especially when using WHERE clauses?

Prepared statements in PHP can help optimize queries, especially when using WHERE clauses, by allowing the database to prepare the query once and execute it multiple times with different parameters. This eliminates the need for the database to recompile the query every time it is executed, resulting in improved performance and reduced overhead.

// Using prepared statements to optimize queries with WHERE clauses
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

// Prepare a statement with a placeholder for the WHERE clause
$stmt = $pdo->prepare("SELECT * FROM mytable WHERE column = :value");

// Bind the parameter to the placeholder
$value = "example";
$stmt->bindParam(':value', $value);

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

// Fetch the results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Loop through the results
foreach ($results as $row) {
    // Process the data
}