views:

105

answers:

3

Is it a must to close the connection in PHP script?

A: 

When the php scrip finishes running, all objects, variables are lost even the db connection.else with the new db connection object. But as rule of thumb, it is better to open connection and close it when you don't need it.

Sarfraz
+3  A: 

Yes, it is. As a general rule is this: open connections as late as possible, and close them as soon as possible. In most modern systems/environments connections are pooled, so there's no problem (performance hit) in constantly opening and closing them.

Anton Gogolev
+5  A: 

Depending on the configuration of your DB server, there is a limit on the possible number of connections opened to it at the same time.

So, if your script :

  • does some queries
  • and, then, does some long calculations without doing any query anymore

It can be interesting to close the connection after having done all your queries -- and to only open the connection when it's becoming needed.


Still, note that connections are closed when the script ends, anyway ; which means that if you don't have a wya to be sure that you have finished doing queries, you don't need to close the connection : keeping it opened allows you to do some additionnal queries whenever it's necessary.

(This is particularly true is your pages are built using several distinct and independant components, that are all susceptible to do DB queries)


For the applications I write, I generally :

  • Open the connection on the first query (Which means no connection is opened if no query is sent)
  • Never close the connection : as my pages asre built using lots of components, I have no way of knowing for sure that the connection won't be needed anymore.
Pascal MARTIN