What are best practices for handling database connections in PHP scripts to avoid errors like "Could not connect to the database"?

When handling database connections in PHP scripts, it's important to properly handle errors to avoid issues like "Could not connect to the database." One way to do this is by using try-catch blocks to catch any exceptions that may occur during the connection process. Additionally, it's good practice to close the connection after using it to free up resources.

<?php

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully";
} catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}
$conn = null; // Close the connection