How can one handle errors related to MySQL queries in PHP effectively?

When handling errors related to MySQL queries in PHP, it is important to use error handling mechanisms provided by PHP and MySQL to effectively capture and handle any errors that may occur during query execution. One common approach is to use try-catch blocks to catch exceptions thrown by the MySQL query execution and handle them accordingly.

<?php
// Establish a connection to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

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

    // Execute a query that may throw an exception
    $stmt = $conn->query("SELECT * FROM table_name");

    // Process the query results
    while ($row = $stmt->fetch()) {
        // Handle the query results
    }
} catch(PDOException $e) {
    // Handle any exceptions thrown during query execution
    echo "Error: " . $e->getMessage();
}

// Close the database connection
$conn = null;
?>