How can error handling be implemented in PHP code that interacts with a MySQL database to provide more informative feedback?

When interacting with a MySQL database in PHP, error handling can be implemented using try-catch blocks to catch exceptions and provide more informative feedback to the user. By using the PDO (PHP Data Objects) extension, we can set the PDO::ATTR_ERRMODE attribute to PDO::ERRMODE_EXCEPTION to automatically throw exceptions when errors occur during database operations.

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

    // Perform database operations here

} catch (PDOException $e) {
    echo "An error occurred: " . $e->getMessage();
}