Connection error with PHP PDO triggers warning and script runtime

I am trying to instantiate a PDO object as follows:

$this->pdo['pdo'] = new PDO('mysql:host=127.0.0.1;dbname=mydb;charset=UTF-8', 'myuser', 'my pass'); 

I would like to get an exception that I thought would be thrown when the MySQL server is not running.

PHP.net says: "PDO :: __ construct () throws a PDOException if an attempt to connect to the requested database fails."

But if I close 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 to catch the error (without the hassle of temporarily setting up the function of the custom error manager?)

Thanks!

+6
source share
2 answers

Pass the array configuration as the 4th parameter of PDO ():

 PDO::setAttribute ( PDO::ATTR_TIMEOUT , '5' ); //> Secs 

To reduce connection timeouts

and

 PDO::setAttribute ( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 

always throws an exception.

Using:

 new PDO(,array( PDO::ATTR_TIMEOUT => "10", PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION )); 
+4
source

I had a similar problem. I finally decided.

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

When I do 3 or 4 loops, everything is fine. When I have 5000 iterations, my mySQL server seems to block me, and then I get the error message "Warning: PDO :: __ construct () [pdo .-- construct]: [2002]" Connection error ... "

I know that it wasn’t too smart to put a “new PDO (..." in the loop. Hope this helps you guys.

Antoine

0
source

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


All Articles