How can error handling be improved in PHP code to provide more informative feedback to users when database queries fail?

When database queries fail in PHP, error handling can be improved by using try-catch blocks to catch exceptions and provide more informative feedback to users. By catching exceptions, we can log detailed error messages, display user-friendly error messages, and gracefully handle errors without crashing the application.

try {
    // Perform database query
    $result = $pdo->query("SELECT * FROM users");
    
    // Process query result
    foreach($result as $row) {
        // Do something with the data
    }
} catch (PDOException $e) {
    // Log the error message
    error_log('Database query failed: ' . $e->getMessage());
    
    // Display a user-friendly error message
    echo 'An error occurred while processing your request. Please try again later.';
}