What are some recommended methods for error handling and displaying meaningful messages when working with PHP and MySQL queries?

When working with PHP and MySQL queries, it is important to implement proper error handling to catch any potential issues that may arise during database interactions. One recommended method is to use the try-catch block to catch exceptions thrown by the database connection or query execution. Additionally, displaying meaningful error messages can help in troubleshooting and debugging any issues that occur.

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 WHERE id = :id");
    $stmt->bindParam(':id', $userId);
    $stmt->execute();

    $result = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$result) {
        throw new Exception("User not found");
    }

    // Process the query result here

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