What are best practices for connecting and disconnecting from a database using PHP?

When connecting to a database using PHP, it is important to establish a connection using the appropriate credentials and close the connection when it is no longer needed to free up resources. It is recommended to use PHP's PDO (PHP Data Objects) or MySQLi extension for connecting to databases as they provide secure and efficient ways to interact with databases.

// Connecting to a MySQL database using PDO
$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();
}

// Disconnecting from the database
$conn = null;