What best practices should be followed when handling MySQL connection errors in PHP scripts?

When handling MySQL connection errors in PHP scripts, it is important to check for errors after attempting to connect to the database and handle them gracefully. This can be done by using try-catch blocks to catch any exceptions thrown by the connection attempt and display an appropriate error message to the user.

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // Set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully"; 
} catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}
?>