What best practices should PHP developers follow when handling database connections in their scripts?

PHP developers should follow best practices when handling database connections in their scripts to ensure security, efficiency, and maintainability. One common practice is to use PDO (PHP Data Objects) for database connections, as it provides a secure way to interact with databases and supports multiple database types. Developers should also use prepared statements to prevent SQL injection attacks and properly handle errors to ensure graceful degradation in case of connection issues.

// Establishing a PDO database connection
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'username';
$password = 'password';

try {
    $pdo = new PDO($dsn, $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}