Search code examples
phpsymfony1doctrinedatabase-connectionpropel

Use of closing database connection in php


I was always in assumption that it is always a good practice to close database connection, regardless of database/ORM, like mysql_close(), Propel::close() etc.

With reference to one of my other question and some other research on Internet, I came to know a surprising face that most people recommends it doesn't really matter if you close connection as connection always gets closed after the request.

However I'm finding those answers little difficult to digest. Reason is, why all DB lib, ORM provide close method? If it is there, in every ORM/lib, there must be some good use of it.

Can someone please shed some light on under what circumstances, we should use close method to close DB connection? & if these methods are not useful at all, why they are present there in all db libs/ORM?

EDIT

My Conclusion

It was a good discussion between Bondye and Fluffeh and it cleared my doubts about use of connection closing. Thanks to both of them.

  • If your script is expected to last of less than 100 ms, dont bother closing connection.
  • BUT: if script is expected to last longer and there is some time between last DB operation and close of script, free connection for others by calling *close().

It is really very difficult for me to accept one answer as both answer are correct on its place. Just accepting answer with all comments so that it remain on top. But +1 to both correct answers.


Solution

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

    Freeing resources

    Thanks to the reference-counting system introduced with PHP 4's Zend Engine, a resource with no more references to it is detected automatically, and it is freed by the garbage collector. For this reason, it is rarely necessary to free the memory manually.

    Hope this helps you more.

    (source)

    edit:

    The purpose of mysql_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 clients. Naturally this is a bad thing, so, as with mysql_free_result(), it is good to call mysql_close() if you think there will be some time between your last database use and your script ending.