How can we handle error messages effectively when executing SQL queries in PHP?

When executing SQL queries in PHP, it is important to handle error messages effectively to troubleshoot any issues that may arise. One way to do this is by using try-catch blocks to catch any exceptions thrown by the database connection or query execution. By catching these exceptions, we can output detailed error messages to help us identify and resolve the problem.

try {
    // Connect to the database
    $conn = new PDO("mysql:host=localhost;dbname=myDB", "username", "password");
    
    // Execute SQL query
    $stmt = $conn->query("SELECT * FROM myTable");
    
    // Fetch results
    $results = $stmt->fetchAll();
    
    // Output results
    print_r($results);
    
} catch (PDOException $e) {
    // Handle any database errors
    echo "Error: " . $e->getMessage();
}