Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

i would suggest running the database queries within a try..catch block, like so:

try {
    $dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
    // Do something here
} catch (PDOException $e) {
    print "Error!: " . $e->getMessage();
    die();
} 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top