Is it better to open the database once on the first page load and close it on browser exit in PHP applications?

It is generally better to open the database connection once on the first page load and close it on browser exit in PHP applications to improve performance and reduce unnecessary database connections. This approach minimizes the overhead of establishing a new connection for each page request, leading to faster response times and better resource management.

// Open database connection on first page load
$connection = new mysqli($servername, $username, $password, $dbname);

// Close database connection on browser exit
register_shutdown_function(function() use ($connection) {
    $connection->close();
});