What are some best practices for handling error messages in PHP scripts, especially when dealing with database queries?

When handling error messages in PHP scripts, especially when dealing with database queries, it is important to properly handle potential errors to ensure smooth operation of the script. One best practice is to use try-catch blocks to catch exceptions thrown by database queries and handle them appropriately, such as displaying an error message to the user or logging the error for later investigation.

try {
    // Perform database query
    $query = "SELECT * FROM users";
    $result = $pdo->query($query);

    // Process query result
    foreach ($result as $row) {
        // Do something with each row
    }
} catch (PDOException $e) {
    // Handle database query error
    echo "Error executing query: " . $e->getMessage();
    // Log the error for later investigation
    error_log("Database query error: " . $e->getMessage());
}