How can PHP developers effectively handle errors and exceptions when working with database queries?

When working with database queries in PHP, developers can effectively handle errors and exceptions by using try-catch blocks to catch any potential exceptions that may arise during the query execution. By wrapping the database query code in a try block and using catch blocks to handle specific exceptions, developers can gracefully handle errors and prevent them from crashing the application.

try {
    // Connect to the database
    $pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
    
    // Prepare and execute the query
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
    $stmt->bindParam(':id', $userId);
    $stmt->execute();
    
    // Fetch the results
    $result = $stmt->fetch();
    
    // Handle the results
    // ...
    
} catch (PDOException $e) {
    // Handle any database connection or query errors
    echo "Database Error: " . $e->getMessage();
}