What are some best practices for handling database connections in PHP?

When handling database connections in PHP, it is important to establish a connection only when needed and close it when no longer in use to avoid resource wastage and potential security vulnerabilities. It is recommended to use PDO (PHP Data Objects) for database operations as it provides a secure and efficient way to interact with databases.

// Establishing a PDO database connection
try {
    $pdo = new PDO('mysql:host=localhost;dbname=my_database', 'username', 'password');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Error connecting to database: " . $e->getMessage());
}

// Perform database operations here

// Closing the database connection
$pdo = null;