PHP Database Design – Should Database Connections Be Closed After Use?

databasedesignPHP

I wonder if I should close any unnecessary database connection inside of my PHP scripts.

I am aware of the fact that database connections are closed implicitly when the block stops executing and 'manually' closing the connections could kinda bloat the codebase with unnecessary code.

But shouldn't I do so in order to make by code as readable and as easy understandable as possible, while also preventing several possible issues during run time?

Also, if I would do, would it be enough to unset() my database object?

Best Answer

For the purpose of safe coding, you should always close database connections explicitly to make sure that the code was able to close itself gracefully and to prevent any other objects from reusing the same connection after you are done with it.

Using unset is the same as leaving the database connection open, as you're relying on the garbage collector to clean up after the variable as opposed to asking the connection to gracefully close the connection after you're done with it. Though as mentioned by CodeCaster below, doing so is acceptable since the garbage collector makes sure that the connections are closed.

A useful example, lets say you're eating lunch at a cafeteria somewhere. After eating, you have two choice, throw your left overs in the trash then return the plate/tray to its rightful place(thats cleaning up after yourself). And the other is just leaving your mess on the table and wait for someone else(the garbage collector) to clean it up for you.

If you clean it up yourself, you're sure that your mess is cleaned up. But if you rely on the garbage collector, right before the garbage collector cleans up your mess, what if some weird stalker decides to use your used utensils to aid them in their nightly fantasies about you, then return them back to the cafeteria just in time for the garbage collector to clean up your mess. Stuff like that can happen.

EDIT: Corrected my mistake about garbage collectors.

Related Topic