Last active
January 5, 2016 16:58
-
-
Save jurchiks/c8fff1e5ec8c97005425 to your computer and use it in GitHub Desktop.
php pdo query() throws error AND exception when mysql server has gone away
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
PHP Warning: PDO::query(): MySQL server has gone away in C:\Users\Juris\Desktop\test\test.php on line 23 | |
Warning: PDO::query(): MySQL server has gone away in C:\Users\Juris\Desktop\test\test.php on line 23 | |
PHP Warning: PDO::query(): Error reading result set's header in C:\Users\Juris\Desktop\test\test.php on line | |
23 | |
Warning: PDO::query(): Error reading result set's header in C:\Users\Juris\Desktop\test\test.php on line 23 | |
Exception: connection problem. Message: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
try | |
{ | |
$connection = new PDO( | |
'mysql:dbname=test;host=localhost;port=3306;', | |
'username', | |
'password', | |
[ | |
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, | |
] | |
); | |
} | |
catch (PDOException $e) | |
{ | |
echo 'Failed to initialize database connection. Message: ', $e->getMessage(), PHP_EOL; | |
die(); | |
} | |
try | |
{ | |
$connection->exec('SET SESSION wait_timeout = 1'); // make the connection close after 1 second, for test purposes | |
sleep(3); // wait for the connection to die | |
$sum = $connection->query('SELECT 1 + 1')->fetchColumn(0); // query() should throw an exception, because ERRMODE is set to EXCEPTION | |
if (intval($sum) === 2) | |
{ | |
echo 'connection is good', PHP_EOL; | |
} | |
else | |
{ | |
echo 'connection problem', PHP_EOL; | |
} | |
} | |
catch (PDOException $e) | |
{ | |
echo 'Exception: connection problem. Message: ', $e->getMessage(), PHP_EOL; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment