What are best practices for handling database connection errors in PHP scripts?

Database connection errors in PHP scripts can be handled by using try-catch blocks to catch exceptions thrown by database connection functions. This allows for graceful error handling and prevents the script from crashing if a connection error occurs. Additionally, using error reporting functions like mysqli_error() or PDOException->getMessage() can provide more detailed information about the error for debugging purposes.

<?php

try {
    $conn = new PDO("mysql:host=localhost;dbname=myDB", "username", "password");
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}

// Perform database operations here

$conn = null; // Close the database connection