What are the best practices for error handling in PDO when executing SQL queries?

When executing SQL queries using PDO, it is important to properly handle errors to ensure the stability and security of your application. One best practice is to set PDO to throw exceptions on errors, which can be caught and handled accordingly in your code. Additionally, utilizing try-catch blocks when executing queries can help you capture and handle any exceptions that may occur.

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

    // Example query
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
    $stmt->bindParam(':id', $userId);
    $stmt->execute();

    // Fetch results
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

} catch (PDOException $e) {
    echo "Error executing query: " . $e->getMessage();
}