Do I really need to do mysql_close()? Why or why not?
Is there a trigger that closes the link after mysql_connect even if I don't do mysql_close?
Description. Closes a previously opened connection. mysql_close() also deallocates the connection handler pointed to by mysql if the handler was allocated automatically by mysql_init() or mysql_connect() .
mysql_select_db() sets the current active database on the server that's associated with the specified link identifier. If no link identifier is specified, the last opened link is assumed. If no link is open, the function will try to establish a link as if mysql_connect() was called without arguments, and use it.
You can also terminate the session by issuing an EXIT statement or (under Unix) by typing Ctrl-D. The way you specify connection parameters for mysql also applies to other MySQL programs such as mysqldump and mysqladmin.
According to the documentation:
Using mysql_close() isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.
Personally, I always like to make sure I pedantically close anything that I open, but it's not required.
In most cases calling mysql_close
will not make any difference, performance-wise. But it's always good practice to close out resources (file handles, open sockets, database connections, etc.) that your program is no longer using.
This is especially true if you're doing something that may potentially take a few seconds - for instance, reading and parsing data from a REST API. Since the API call is going over the line, negative network conditions can cause your script to block for several seconds. In this case, the appropriate time to open the database connection is after the REST call is completed and parsed.
To sum up my answer, the two big rules are:
what's the benefit of closing the link?
The benefit is that you can free the connection to the database, and corresponding resources in the database server, earlier than the PHP request cleanup would do it.
Say for example you query all the data your request will need in the first 20 milliseconds of the request. But then your PHP code spends another 80 milliseconds running code and formatting the results. Which means 80% of the time, the app is holding open a db connection without needing to, and on average, 8 out of 10 connection threads on the db server are idle and using resources.
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