How can error handling be implemented effectively when executing SQL queries in PHP?

When executing SQL queries in PHP, it is important to implement error handling to catch any potential issues that may arise during the query execution. This can be done by using try-catch blocks to capture exceptions thrown by the database connection or query execution. By handling errors gracefully, you can provide meaningful feedback to the user and prevent any unexpected behavior in your application.

try {
    $pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $stmt = $pdo->prepare("SELECT * FROM users");
    $stmt->execute();
    
    // Process the query results here
    
} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}