What are best practices for error handling when connecting to a database in PHP?

When connecting to a database in PHP, it is important to implement proper error handling to catch any potential issues that may arise, such as connection failures or query errors. One best practice is to use try-catch blocks to catch exceptions and handle them gracefully, providing meaningful error messages to the user or logging them for debugging purposes.

<?php
try {
    $pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected to database successfully";
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}
?>