I get the following error:
Link to server lost, unable to reconnect
I have a mysql daemon coded, and I use mysql_pconnect to connect to mysql but after a while, I get the following error and the daemon stops functioning properly:
Link to server lost, unable to reconnect
What I do is the following:
while(true)
{
$connect = mysql_pconnect(...);
$db = mysql_select_db(...);
}
What can I do to prevent this? I need mysql connection to stay steady for the whole duration of the daemon – which may be forever.
You have a few choices.
But just as a precursor, you should try and move away from relying on mysql_* and start using the PDO instead.
Anyway…
When you open a mysql connection, it will stay “available” until the wait timeout has expired. What you are doing is constantly creating a new connection, (also without closing the other connection). This means you will either hit the server mysql limit, or your unix box socket limit very quickly.
Wait Timeout
You should first check with your server to see what this timeout is set to.
You might want to consider increasing it in your my.cnf if it is terribly low. The default period is
28800seconds (if I recall correctly).You can check by issuing this query:
You can then change the value in your my.cnf to increase it or you can also set it using
SELECT 1
Okay, now, with a reasonable set timeout set, the “typical” way that you can make sure that you don’t get the
mysql has gone awaymessage, is to just do aSELECT 1. This will do another query and make sure that the connection is held open.And, the benefit of using the PDO is that you can then catch PDOExceptions which might be thrown when a SELECT 1 fails.
This means, that you can then try and connect again, if an exception is thrown, and then check again. If you can’t connect after that then you should probably kill your daemon.
Here is some code…. you would clearly have to make your PDO object using a valid connection string.
This is the solution that I would probably take.
You can easily substitute the
SELECT 1with your own query that you actually want to use. This is just an example.