开发者

PHP PDO connection failure throws warning and script execution times out

开发者 https://www.devze.com 2023-03-16 12:04 出处:网络
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\',

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 beca开发者_如何学JAVAuse 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         

));


I had a similar issue. I finaly solved it.

The thing is, I had a "new PDO('mysql:host=127.0.0.1;dbname=mydb','myuser', 'my pass');" into a for/while loop.

When I do 3 or 4 loops it is all right. When I have 5000 iterations, my mySQL server seems to block me and then I get the "Warning: PDO::__construct() [pdo.--construct]: [2002] 'A connection attempt fail..." error message.

I know this wasn't too clever to put a "new PDO(..." into a loop. Hope this will help you guys.

antoine

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号