What measures should be taken to handle errors and exceptions when executing MySQL queries in PHP code?

When executing MySQL queries in PHP code, it is important to handle errors and exceptions properly to ensure that any issues are caught and dealt with appropriately. One way to do this is by using try-catch blocks to catch exceptions that may occur during the query execution. Additionally, checking the return value of the query execution function can help identify any errors that may have occurred.

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

    $query = "SELECT * FROM mytable";
    $statement = $connection->query($query);

    if ($statement) {
        // Process the query results
    } else {
        throw new Exception("Error executing query");
    }
} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}