How can proper error handling techniques be implemented when working with MySQL queries in PHP?

When working with MySQL queries in PHP, proper error handling techniques can be implemented by using try-catch blocks to catch any exceptions that may arise during the query execution. Inside the catch block, you can handle the error by logging it, displaying a user-friendly message, or taking any other appropriate action.

try {
    $connection = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
    $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    $query = "SELECT * FROM mytable";
    $stmt = $connection->query($query);
    
    // Process the query result
    
} catch (PDOException $e) {
    // Handle the error
    echo "An error occurred: " . $e->getMessage();
}