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

When handling database connections in PHP, it is important to follow best practices to ensure efficient and secure communication with the database. One common approach is to use PDO (PHP Data Objects) to connect to the database, as it provides a secure way to interact with different database management systems. It is also recommended to use prepared statements to prevent SQL injection attacks and to properly handle exceptions to catch and handle any errors that may occur during the database interaction.

// Establishing a database connection using PDO
$host = 'localhost';
$dbname = 'my_database';
$username = 'my_username';
$password = 'my_password';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected to the database successfully";
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}