Mysqli when and how many times to close connection

Hi all

Ok i was able to connect to mysqli db

now i want to know when and how many times i should use mysqli_close in my code ??

do i have to write “mysqli_close” after every select, insert and update query ??

vineet

The best practice is
Open the connection: As late a possible
Close the connection: As earlier as possible

Rest depands on the type of code. My be your concern is the cpu overhead of opening and closing the sql connection.

However if you want let the connection open for some time. In that case you should take care about the security during that time.

If connection is open its easy to attack on database.

No, that means you will need to re-open for any subsequent query.
Open once before the first query and close once, after your last query.

hi enpriya

its not about cpu overhead.
i had just started using mysqli and where ever i read article in their examples they close the mysqli connection in every code example or snippet .
thats why i was confused

vineet

Hi Sam

this means i will not add “mysqli_close” in the config file or the database connection file which i am including on top of every page

or do i need to add “mysqli_close” in the db connection file ??

vineet

If seen an example of a script in the past which opened and closed database connections for each query, this script happened to fire off about 80 queries and so the time taken for the script was very slow to the point of timing out. When the owner of the script switched to reusing a single connection for the script, it made a MASSIVE difference to the run time of the script

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.