How can errors related to MySQL connections be effectively handled in PHP scripts?

When handling errors related to MySQL connections in PHP scripts, it is important to use try-catch blocks to catch any exceptions that may occur during the connection process. This allows for more controlled error handling and the ability to display meaningful error messages to the user.

<?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);
    echo "Connected successfully";
} catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}

?>