Should I close the MySQL DB in PHP Script?

Hi

Just curious about the MySQL db.

I usually use a mysql db class in my php scripts and everything goes well.

But I never close the active connection, using mysql_close();

is it any bad of not closing the database ?

If you didn’t use a persistent connect to access it to start with then it will close automatically when the script finishes.

Normally it’s fine to let php close it for you at the end of script execution, considering php scripts usually execute for short periods of time. But if the script will run for a long time, you might consider manually closing it early. In extreme cases you might even close, then reopen a connection. eg

open db
query db for data
close db

…do something that takes a long long time…

open db
query db

In most of those cases a better solution is to redesign the script so that it only runs a short time but runs more frequently. Long running scripts are generally scheduled rather than visitor triggered and so running it for a shorter time but more frequently will often achieve the same end result with a better spread of the load.

No script generating a web page should be running for anywhere near long enough to need to close the db before the fraction of a second the script is running for is up.

If you didn’t use a persistent connect

If you use one, you shouldn’t worry either. Because you just can’t close connection in this case :slight_smile:

Exactly - and that’s the only time a connection can outlive a PHP script execution and still be around a fraction of a second later after the PHP finishes.

A common example is using a php script to serve a file download. It could run for a pretty decent amount of time.

I agree that such a script shouldn’t need to hold the database connection for very long and so closing would be very appropriate in that case.

Hats off to all of you !

Thanks a lot Sirs !