What are the advantages and disadvantages of opening and closing the database on each page load in PHP?

Opening and closing the database on each page load in PHP can lead to increased resource usage and slower performance, as it requires establishing a new connection each time. It is more efficient to open the database connection once at the beginning of the script and close it at the end to avoid unnecessary overhead. However, keeping the connection open for the duration of the script may not be suitable for long-running scripts or high traffic websites.

<?php
// Open database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Perform database operations

// Close database connection
$conn->close();
?>