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?
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With