tags:

views:

106

answers:

4

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?

+4  A: 

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.

Dean Harding
what;s the benefit of closing the link?
denniss
There is no benefit to closing the link yourself.
Charles
+1  A: 

The manual says:

Using mysql_close() isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.

So, no, not really. It is helpful to free up resources before attempting an operation that potentially consumes large amounts of resources though, but it probably won't make a big difference.

deceze
+2  A: 

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:

  1. Only allocate resources (file handles, sockets, database connections, etc.) when your program is ready to use them.
  2. Free up resources immediately after your program is done with them.
pygorex1
A: 

what;s the benefit of closing the link?

Normally, there is no benefit in closing the link yourself, as it will be automatically closed.

I can only think of a couple of benefits

  • If your script had a lot of processing to do after it had finished using the database, closing the database link prematurely may help free up a little bit of memory and other resources (such as MySQL connections) while your script continued with other things. This is very unlikely to be an issue in most scripts.

  • Completeness and cleanliness of code. It can give you a good feeling, and is generally good code hygiene to close what you have opened, even though in this case it isn't technically required.

thomasrutter
If you're limiting the number of connections to your database, using mysql_close() releases one of those connections allowing other scripts access
Mark Baker