What are the best practices for handling errors in database connections in PHP?

When handling errors in database connections in PHP, it is important to use try-catch blocks to catch exceptions and handle them appropriately. This ensures that any errors that occur during the database connection process are properly managed and do not crash the application. Additionally, logging the errors can help in troubleshooting and debugging the issue.

try {
    $pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
} catch (PDOException $e) {
    // Handle the error, log it, and display an appropriate message to the user
    echo "Connection failed: " . $e->getMessage();
}