Are there any specific best practices for managing database connections in PHP applications?

Managing database connections in PHP applications involves ensuring that connections are opened and closed efficiently to avoid performance issues and potential security vulnerabilities. One best practice is to use a connection pooling mechanism to reuse existing connections rather than creating new ones for each request.

// Create a database connection using PDO
$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());
}

// Use $pdo to interact with the database

// Close the database connection when done
$pdo = null;