mysql_connect doesn't work second time

2019-07-20 12:57发布

问题:

duplicate of unanswered: How to reconnect in php adodb after exceptions: Mysql server gone away or Lost connection to MySQL server during query

mysql_connect works the first time, but never works after that...

$connectDb = mysql_connect(secret, secret, secret);
mysql_select_db("secret", $connectDb);

$sleepPeriod = 1800;
sleep($sleepPeriod);
while (true) {
  $result = mysql_query("good query", $connectDb);
  if (!$result) {
    if (mysql_error()=='MySQL server has gone away') {
      echo "MySql connection was disconnected... reconecting...\n";
      $connectDb = mysql_connect(secret, secret, secret);
      mysql_select_db("secret", $connectDb);
      continue;
    } else {
      die("Invalid Query: ".__FILE__.':'.__LINE__.' '.mysql_error()."\n");
    }
  }
  //DO STUFF
  sleep($sleepPeriod);
}

if a timeout or disconnect happens mysql_connect seems to fail and mysql_error continually returns "MySQL server has gone away", which results in an infinite loop that can go for days. is there some other way to clear the error response of mysql_error or to make mysql_connect run a second time without having to restart this program manually or resorting to cron.

I just noticed that mysql_connect has a strange(stupid?) parameter called new_link, however it would be an outrageous design if php's mysql code purposefully disables reconnects on timeout by default... I'll test regardless and get back.

回答1:

mysql_connect doesn't care if the connection has disconnected or timed-out it will never connect a second time unless you call it with the parameter new_link with the value true.

mysql_connect($server,$username,$password,true);