Question

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?

Was it helpful?

Solution

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();

OTHER TIPS

FYI: this has been reported as a bug several times 1,2,3 with no fix so far (5.3.14). The only solution is to do a new connection each time after forking a child, and also set PDO::ATTR_PERSISTENT => false

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top