I am trying to instantiate a PDO object like this:
$this->pdo['pdo'] = new PDO('mysql:host=127.0.0.1;dbname=mydb;charset=UTF-8',
'myuser', 'my pass');
I'd like to catch the exception that I thought would be thrown when the MySQL server is not running.
PHP.net says "PDO::__construct() throws a PDOException if the attempt to connect to the requested database fails."
But if I shut down the database server and run the script all I get is a warning:
Warning: PDO::__construct() [pdo.--construct]: [2002] 'A connection attempt failed
because the connected party did not properly respond after a period of time, or
established connection failed because connected host has failed to respond.' in
C:\test\test.php on line 5
Fatal error: Maximum execution time of 60 seconds exceeded in C:\test\test.php
on line 0
No exception is thrown.
Is there a direct way of catching the error (without the hassle of temporary setting a custom error manager function?)
Thanks!
Pass the array config as 4th param of PDO():
PDO::setAttribute ( PDO::ATTR_TIMEOUT , '5' ); //> Secs
To lower the connection timeout
and
PDO::setAttribute ( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
to always throws Exception.
Usage:
new PDO(,array(
PDO::ATTR_TIMEOUT => "10",
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
));
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