mysql server has gone away in PDO

Tanu Gupta picture Tanu Gupta · Aug 17, 2012 · Viewed 8.5k times · Source

I am running my php script and getting an intermittent issue:

PHP Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000]: General error: 2013 Lost connection to MySQL server during query'

Is it possible to ping mysql in PDO if such error occurs?

I just want to bring this in your notice that my PDO connection is not persistent. I am connecting PDO in loop. I suppose every time a new connection will open up in loop. If this is so, then why mysql is losing connection? Or it may possible that if a PDO connection already exists then it gives the existing pdo object. but if such error occurs, it should try to reconnect and give the new connection instead of error.

Any possible solution to avoid the error?

Answer

Tanu Gupta picture Tanu Gupta · May 16, 2013

In my case, PDO was taking single connection and if the loop size is big, connection was getting timed out. So, I increased the timeout of PDO connection for all cli's.

$this->connection = new PDO($this->dsn, $this->username, $this->password);
//Increase the session time out for all cli's
if(php_sapi_name() == 'cli'){
      $query = $this->connection->prepare("set session wait_timeout=10000,interactive_timeout=10000,net_read_timeout=10000");
      $query->execute();
}

Issue is resolved now.