What are the best practices for handling PHP code errors related to database connections, especially when multiple instances of the code are used on a single webpage?

When handling PHP code errors related to database connections, especially when multiple instances of the code are used on a single webpage, it is best practice to implement error handling to gracefully handle any potential issues. This can include using try-catch blocks to catch exceptions, checking the connection status before executing queries, and providing meaningful error messages to the user.

<?php
try {
    $db = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    // Perform database operations here
} catch (PDOException $e) {
    echo "Error connecting to database: " . $e->getMessage();
}
?>