Reputation: 7821
I am a paranoid kind of guy and even though I included mysql_close()
in my PHP functions after I do something, is there a way I can check (besides another query) to see if the connection is still open, just for assurance.
Upvotes: 1
Views: 2597
Reputation: 3510
AFAIK if you open mysql connection with mysql_pconnect(), they don't really clossed after mysql_close(), it's just return to connection pool
Upvotes: 0
Reputation: 44373
You may want to try mysql_ping()
Here is an excerpt from that page:
bool mysql_ping ([ resource $link_identifier ] )
Checks whether or not the connection to the server is working.
If it has gone down, an automatic reconnection is attempted.
This function can be used by scripts that remain idle for a long while,
to check whether or not the server has closed the connection and
reconnect if necessary.
Note: Since MySQL 5.0.13, automatic reconnection feature is disabled.
As for this excerpt, I do not know whether the automatic reconnection feature is disabled comment refers to mysql or PHP. You will have to experiment with it to find out. If this reconnection issue is indeed true, then @Brad's answer is paranoid-proof since you could run mysql_close immediately after querying the data and fetching it. You can be sure at that point that there is no valid connection since you explicitly closed it. Consequently, you would have to run mysql_connect for your next query.
However, letting non-persistent connections close on there own is not always a good idea because this could potentially stockpile TIME_WAITs in the DB Server's netstat. This would fool webservers into thinking that DB Connections are no longer available because MySQL ran out where the OS would actually be the cause since it would delay releasing Connection Resources. To be better safe that sorry, run mysql_close when done and mysql_connect/mysql_query for the next query.
If you are willing, you could construct a try-catch paradigm or a set of if-then-else stataments to first run mysql_ping on an established connection. If true, use it with mysql_query. Otherwise, run mysql_close/mysql_connect/mysql_query.
Upvotes: 1
Reputation: 163612
The mysql_close()
function returns true
if it succeeded. By adding an extra check outside of checking the return value of mysql_close()
, you aren't doing anything helpful, and adding another place bugs can crop up in your code.
In any case, non-persistent connections are closed automatically when your script finishes, so it isn't necessary, unless you have some specific reason to kill off the resource ahead of time.
Upvotes: 5
Reputation: 50982
$con = mysql_connect("localhost" ,"name", "pass");
/* your code*/
if ($con){
mysql_close();
}
Upvotes: 0