Is there any reason why I should close the connection after a query or at the end of the script?
What are the benefits of doing/no doing do?
The purpose of mysqli_close() is also to save computer resources, but another key reason for using it is because there is a limited number of connections that a MySQL server can accept, and if you have several clients holding connections open for no reason then the server may well need to turn away other, waiting ...
The close() / mysqli_close() function closes a previously opened database connection.
Closing your connection allows for your resources to be reallocated.
If your script has a fair amount of processing to perform after fetching the result and has retrieved the full result set, you definitely should close the connection. If you don't, there's a chance the MySQL server will reach it's connection limit when the web server is under heavy usage.
The connection (if not persistent) is always closed at the end of the script, so, in theory, you don't need to close it yourself.
Still, if your PHP script takes lots of time to execute, it's a good idea to close the connection when you don't have to do any request to the database anymore -- at least, if the long calculations are done after the queries.
This is especially true if your application is deployed on a shared hosting : your user account can generally only have a few connections opened at the same time. (That number of simultaneous opened connections can be pretty small on shared hosting ; it's generally bigger on private servers).
The reason we often don't close connections ourselfves is :
The benefit is if you're going to be doing long-running processing but have finished querying the database then there is no point holding open a connection. The same goes for holding the user session open (which blocks other requests).
An example of this might be creating a large PDF report. This might take you 20-30+ seconds to create and write out the file but you get all the data you need in the first second.
Ordinarily however you may as well do it automatically (assuming the connection isn't persistent).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With