What are some best practices for error handling in PHP scripts that involve database queries?

When handling errors in PHP scripts that involve database queries, it is important to use try-catch blocks to catch any exceptions that may occur during the query execution. This allows for graceful error handling and prevents the script from crashing. Additionally, using functions like mysqli_error() or PDO::errorInfo() can help retrieve detailed error messages for debugging purposes.

// Example of error handling in a PHP script with a database query

try {
    // Perform database query
    $result = $pdo->query("SELECT * FROM users");
    
    // Process the query result
    foreach ($result as $row) {
        echo $row['username'] . "<br>";
    }
} catch (PDOException $e) {
    // Handle any exceptions that occur during the query execution
    echo "Error: " . $e->getMessage();
}