When do I need to close a database connection in PHP?

I don't look like a php developer, but I need to use it, and I don't know how PHP handles memory allocation during a session.

I am working on an application that requests HTTP authentication. Once you are logged in, you can manage the data through a good interface.
Someone told me in another post that I should not close the mysql data connection after each execution, but I do not know how this connection remains memory while using this application, because on the server side I have no idea what PHP is holding memory or not.

So my question is whether to use a single singlet to connect to db and never close it (because I will never know when the application is not in use. Or should I stand on what I am doing today: opening a connection → execute an operator → close the connection.

PS: I am using mysqli

Edit 1 :
My application has a design with an MVC template meaning:

|''''''''''| |'''''''''''''| |''''''''''''''| | view.php | ==> | control.php | ==> | database.php | |----------| |_____________| |______________| 

This template allows a view to interact with data only through control.php , which then calls a function from database.php data in SELECT or EDIT . with the explanation you give me, I have to put:

 public function __destruct(){ mysql_close($this->connection); } 

inside database.php , but this page loads when there is a need to select or modify data, so it only runs for a short time, that is, it will still close the connection at the end of the request.

Which gives a more accurate question about where should I put the world of code that you provide, or is my template related to PHP?

+8
php mysql mysqli
source share
2 answers

Never create a new connection for each request; You do not even need to close it manually.

Just create a connection at the top of the page

look: How do you effectively connect to mysql in php without reconnecting to every request

you can use this:

 public function __destruct() { mysql_close($this->connection); } 

it will be called when the page is closed

+7
source share

From the PHP Mysqli documentation :

the relationship between the client process and the database can be reused by the client process, rather than being created and destroyed several times. This reduces overhead ...

+2
source share

All Articles