What are the best practices for handling errors and displaying error messages in PHP when dealing with database queries?

When handling errors and displaying error messages in PHP when dealing with database queries, it is important to check for errors after executing the query and handle them appropriately. One common practice is to use try-catch blocks to catch exceptions thrown by the database connection or query execution. Inside the catch block, you can log the error message, display a user-friendly message, or redirect the user to an error page.

try {
    // Database connection code
    
    // Database query execution
    $result = $pdo->query("SELECT * FROM users");
    
    // Check for errors
    if (!$result) {
        throw new Exception("Error executing query");
    }
    
    // Process the query result
    
} catch (Exception $e) {
    // Log the error message
    error_log($e->getMessage());
    
    // Display a user-friendly error message
    echo "An error occurred. Please try again later.";
    
    // Redirect the user to an error page
    // header("Location: error.php");
}