What are the best practices for handling database queries and processing results in PHP for optimal performance?

Issue: To optimize performance when handling database queries in PHP, it is recommended to use prepared statements to prevent SQL injection attacks, minimize the number of queries executed, fetch only the necessary data, and utilize indexes on columns frequently used in queries. PHP Code Snippet:

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

// Prepare a SQL statement with placeholders
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');

// Bind parameters to the placeholders
$stmt->bindParam(':id', $id, PDO::PARAM_INT);

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

// Fetch the results as an associative array
$user = $stmt->fetch(PDO::FETCH_ASSOC);

// Close the connection
$pdo = null;