What are best practices for connecting to and closing a MySQL database connection in PHP?

When connecting to a MySQL database in PHP, it is important to establish a connection using the mysqli or PDO extension, execute queries, and then close the connection to free up resources. To properly close a MySQL database connection in PHP, use the mysqli_close() function or unset the PDO object.

// Connect to MySQL database using mysqli
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

// Execute queries

// Close MySQL database connection
mysqli_close($conn);