What is the best practice for handling database connection errors in PHP?

When handling database connection errors in PHP, it is important to implement error handling to gracefully handle any potential issues that may arise. One common practice is to use try-catch blocks to catch exceptions thrown by the database connection code and handle them appropriately, such as displaying an error message to the user or logging the error for further investigation.

<?php

try {
    $pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
    // Set PDO to throw exceptions on error
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    // Handle the error gracefully
    echo "Connection failed: " . $e->getMessage();
    // Log the error for further investigation
    error_log("Database connection error: " . $e->getMessage());
}

?>