What are the best practices for establishing and managing database connections in PHP scripts?

Establishing and managing database connections in PHP scripts involves ensuring that connections are properly opened and closed to avoid performance issues and potential security vulnerabilities. It is important to use secure methods for connecting to databases, such as PDO or MySQLi, and to handle errors effectively to prevent data loss or corruption.

// Using PDO to establish a database connection
try {
    $pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}

// Perform database operations here

// Closing the database connection
$pdo = null;