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

When dealing with database queries in PHP, it is important to implement proper error handling to ensure that any issues are caught and addressed appropriately. One common practice is to use try-catch blocks to catch exceptions thrown by database operations and handle them accordingly. Additionally, using functions like mysqli_error() or PDO::errorInfo() can help retrieve specific error messages for debugging purposes.

// Example of error handling in PHP when dealing with database queries using PDO

try {
    // Connect to the database
    $pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
    
    // Set PDO to throw exceptions on error
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // Perform a query
    $stmt = $pdo->query("SELECT * FROM my_table");
    
    // Fetch results
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
} catch (PDOException $e) {
    // Handle any database errors
    echo "Error: " . $e->getMessage();
}