What are some 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. Additionally, using error handling functions like mysqli_error() or PDOException can provide more detailed information about the error. Logging errors to a file or sending them to a monitoring service can help in troubleshooting and resolving issues quickly.

try {
    $pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
    // set PDO error mode to exception
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    // log or display the error message
    echo "Connection failed: " . $e->getMessage();
}