What are some best practices for handling SQL queries and result sets in PHP to prevent errors and improve performance?

Issue: To prevent errors and improve performance when handling SQL queries and result sets in PHP, it is important to use prepared statements to prevent SQL injection attacks, properly handle errors, and efficiently manage result sets.

// Example of using prepared statements to prevent SQL injection attacks
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->execute(['username' => $username]);
$results = $stmt->fetchAll();

// Example of properly handling errors
if (!$results) {
    die("Error executing query: " . $stmt->errorInfo());
}

// Example of efficiently managing result sets
foreach ($results as $row) {
    // Process each row of the result set
}