What are best practices for handling database connection errors in PHP?

When handling database connection errors in PHP, it's important to implement error handling to gracefully deal with any potential issues that may arise. One common approach is to use try-catch blocks to catch exceptions thrown by the database connection code and handle them accordingly. Additionally, logging the error messages can help in troubleshooting and debugging any connection problems.

<?php
try {
    $db = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    // Log the error message
    error_log("Connection failed: " . $e->getMessage());
    // Handle the error gracefully, such as displaying a user-friendly message
    echo "An error occurred while connecting to the database. Please try again later.";
}
?>