How can PHP developers handle errors and exceptions effectively when querying databases?

When querying databases in PHP, developers should use try-catch blocks to handle errors and exceptions effectively. By wrapping the database query code in a try block and catching any potential exceptions in a catch block, developers can gracefully handle errors and prevent them from crashing the application.

try {
    // Connect to the database
    $pdo = new PDO('mysql:host=localhost;dbname=database', 'username', 'password');
    
    // Perform the database query
    $stmt = $pdo->query('SELECT * FROM table');
    
    // Fetch the results
    $results = $stmt->fetchAll();
    
    // Process the results
    foreach ($results as $row) {
        // Do something with each row
    }
} catch (PDOException $e) {
    // Handle any database connection or query errors
    echo 'Error: ' . $e->getMessage();
}