How can one optimize PHP code for PDO connections when querying a MySQL database?

To optimize PHP code for PDO connections when querying a MySQL database, it is important to use prepared statements to prevent SQL injection attacks and improve performance. This can be achieved by preparing the query once and then executing it with different parameters, instead of preparing the query each time it is executed.

// Create a PDO connection to the MySQL database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Prepare the query once
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');

// Execute the query with different parameters
$stmt->execute(['id' => 1]);
$results = $stmt->fetchAll();

$stmt->execute(['id' => 2]);
$results = $stmt->fetchAll();