What are some best practices for handling PHP error messages related to database connectivity issues?

When encountering PHP error messages related to database connectivity issues, it is important to properly handle these errors to provide a better user experience. One common best practice is to use try-catch blocks to catch any exceptions thrown when connecting to the database and display a user-friendly error message. Additionally, logging the error details can help in troubleshooting and resolving the issue.

<?php
try {
    $pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
    // Perform database operations here
} catch (PDOException $e) {
    echo "Database connection failed: " . $e->getMessage();
    // Log the error details for troubleshooting
    error_log("Database connection error: " . $e->getMessage());
}
?>