How can error handling be improved in PHP scripts, especially when interacting with databases like MySQL?

To improve error handling in PHP scripts when interacting with databases like MySQL, it is important to use try-catch blocks to catch exceptions that may occur during database operations. This allows for more controlled handling of errors and enables the script to gracefully handle any issues that arise.

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 "Error: " . $e->getMessage();
}