Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do I have to close mysqli (Database) connection?

Tags:

php

mysql

mysqli

For now, I have one connect.php file e.g.

$mysql_host = "";
$mysql_database = "";
$mysql_user = "";
$mysql_password = "";

$con = new mysqli(
    $mysql_host,
    $mysql_user,
    $mysql_password,
    $mysql_database
);

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

In every other PHP file that uses MySQL queries, I use "include 'connect.php';"

For Instance on W3Schools, they create for every query a new connection and then close it after use. See here: w3schools.com: I'm not sure if they do it just for showing purpose, or if it is best practice to do it this way.

Do I have to close the connection after each selection and then establish a new one, for the next query? If not, when do I finally have to close the connection? On the end of the PHP File with all the queries?

like image 239
henk Avatar asked Apr 03 '15 17:04

henk


Video Answer


1 Answers

A quote from the php.net site.

Open non-persistent MySQL connections and result sets are automatically closed when their objects are destroyed. Explicitly closing open connections and freeing result sets is optional. However, it's a good idea to close the connection as soon as the script finishes performing all of its database operations, if it still has a lot of processing to do after getting the results.

Source: http://php.net/manual/en/mysqli.close.php

like image 172
Thais Avatar answered Sep 30 '22 05:09

Thais