In the provided PHP script, what are some best practices for handling database connection errors and displaying relevant error messages?

When handling database connection errors in PHP, it is important to catch any potential exceptions that may occur and display relevant error messages to the user. This can help users understand what went wrong and provide helpful information for troubleshooting. One common best practice is to use try-catch blocks to catch exceptions and display error messages when a database connection error occurs.

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

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();
}
?>