How can the PHP code be modified to handle MySQL errors more effectively and provide better error messages?

To handle MySQL errors more effectively and provide better error messages in PHP, you can use try-catch blocks to catch exceptions thrown by MySQL queries and then display custom error messages based on the specific error encountered.

<?php
$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 your MySQL queries here

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