Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check a PDO MySQL connection for errors BEFORE I run a query?

Tags:

php

mysql

pdo

pcntl

My scripts are getting quite riddled with forked processes in a lot of different functions. Whenever pcntl_fork() is called, all MySQL connections are lost. If I run a query on a PDO MySQL connection I get the error "MySQL server has gone away".

The problem is that this error only shows up in PDO::errorinfo() after a failed query execution. I would like to be able to detect if the MySQL server "has gone away" before I try to run a query. That way I could create a PDO wrapper that makes a new connection for me in such situations.

Any ideas?

like image 774
Hubro Avatar asked Jul 26 '11 15:07

Hubro


Video Answer


1 Answers

I give you 2 methods by example (similar in some ways) :
Example 1 :

$sql = 'SELECT count(*) FROM `TABLE`;';
for ($i = 1; $i <= 2; $i++) {
    try {
        $nb = $pdo->query($sql)->fetchColumn();
        if (is_int($nb)) {
            // OK
            break;
        }
    } catch (PDOException $e) {
    //Oups
        if ($i == 1) {
            // First time ? retry
            $pdo = new PDO($dsn, $user, $password);
        } else {
            // Second time, KO
            $nb = "(unknown)";
            echo 'PDO Connection failed: ' . $e->getMessage().'. ';
        }
    }
}

Example 2 :

// check
try {
    $pdo->query('select 1;')
    //OK
} catch (PDOException $e) {
    //Oups => reconnect
    $pdo = new PDO($dsn, $user, $password);
}
// Should be good
$sql = 'SELECT count(*) FROM `TABLE`;';
$nb = $pdo->query($sql)->fetchColumn();
like image 132
Ka. Avatar answered Sep 30 '22 13:09

Ka.