Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP PDO connection failure throws warning and script execution times out

Tags:

php

pdo

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!

like image 283
Sebastián Grignoli Avatar asked Jun 29 '11 17:06

Sebastián Grignoli


1 Answers

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         

));
like image 106
dynamic Avatar answered Nov 03 '22 13:11

dynamic