What are the best practices for error handling in PHP when dealing with database queries, as seen in the provided code snippet?

When dealing with database queries in PHP, it is important to implement proper error handling to gracefully handle any potential issues that may arise. One common practice is to use try-catch blocks to catch any exceptions thrown by the database connection or query execution. Within the catch block, you can log the error message or take appropriate action based on the specific error.

try {
    // Connect to the database
    $pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

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

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

    // Check if the query was successful
    if (!$result) {
        throw new Exception("No results found");
    }

    // Process the results
    // ...

} catch (PDOException $e) {
    echo "Database error: " . $e->getMessage();
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}