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

My scripts are very riddled with forked processes in many different functions. Whenever pcntl_fork() is called, all MySQL connections are lost. If I run a MySQL PDO connection request, I get the error message "MySQL server has gone away" .

The problem is that this error only appears in PDO::errorinfo() after the query failed. I would like to be able to detect if the MySQL server is β€œgone” before I try to run the query. That way, I could create a PDO wrapper that would create a new connection for me in such situations.

Any ideas?

+6
source share
2 answers

I give you 2 methods using an 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(); 
+2
source

FYI: this is reported as an error several times 1 , 2 , 3 without any corrections (5.3.14). The only solution is to make a new connection every time after the child is expanded, and also set PDO :: ATTR_PERSISTENT => false

+2
source

Source: https://habr.com/ru/post/893600/


All Articles