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

When connecting to a database in PHP, it's important to implement proper error handling to catch any potential issues that may arise during the connection process. One common practice is to use try-catch blocks to handle exceptions thrown by the database connection code. This allows you to gracefully handle errors and display meaningful error messages to the user.

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