tags:

views:

82

answers:

2

What happens if MySQL database is not closed? How do we know if it is closed properly?

I do have a page which has 11 tables on a page..so what I did is I open database on top of page before script starts and close where the scripts(PHP) ends...

the ending is mysql_close($db);...is this fair enough or do I need to give only mysql_close();

A: 

There isn't a point in closing a connection at the end of the script because that is done for you when the script terminates. The only time you should really call the close function explicitly is if you're running a daemon or something and don't want to hold onto a connection for the entire run length.

PDO is considered the modern database access library for PHP (you really should be using this instead of the mysql_* functions, but that's another story) and even that doesn't have a close function, just to drive the point home.

ryeguy
+1  A: 

I can't say for sure if all PHP/Mysql versions on all server platforms behave the same way. For tcp connections to the database - unless you call mysql_close($db), you'll have a dangling tcp connection just sitting there waiting to be used for half a minute after the script ends. Then it'll just go away on its own.

I can't say if this is PHP's garbage collection taking a full 30 seconds to complete, or if the tcp connection is set to expire after 30 seconds on its own once you call connect.

Mysql_close($db) instantly kills the tcp connection though. So yeah, I'd say always call mysql_close($db) immediately after you no longer need a database connection in your script.

bob-the-destroyer