What are best practices for handling MySQL connection errors in PHP code?

When handling MySQL connection errors in PHP code, it is important to check for errors after establishing the connection and handle them gracefully. One common approach is to use try-catch blocks to catch any exceptions that may occur during the connection process 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();
}
?>