Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a connect timeout with PDO

I'm using PDO to get data off a MySQL server. What I noticed is this: if the MySQL server is unavailable, it takes really (relatively) long for this code to return an exception:

try {   $handle = new PDO($db_type . ':host='.$db_host.';dbname='.$db_name,$db_user,$db_pass);   // Tried using PDO::setAttribute and PDO::ATTR_TIMEOUT here } catch(PDOException $e) {   echo $e->getMessage; } 

In case of MySQL it takes just over 2 minutes for the exception to occur (SQLSTATE[HY000] [2003] Can't connect to MySQL server on...) and 30 seconds on PostgreSQL (SQLSTATE[08006] [7] timeout expired).

I tried using PDO::setAttribute and PDO::ATTR_TIMEOUT but it's not working. Which I guess makes sense, since the problem occurs before this statement.

Is there a way to set a timeout for connecting to the DB? 2 minutes/30 seconds seems really long to me for PDO to realize there is nothing there.

I think I saw this being done somewhere, but can't find it again for the life of me.

like image 754
gkres Avatar asked Jan 28 '14 10:01

gkres


People also ask

How do I close a PDO connection?

The connection remains active for the lifetime of that PDO object. To close the connection, you need to destroy the object by ensuring that all remaining references to it are deleted—you do this by assigning null to the variable that holds the object.

What is PDO persistent connection?

The persistent connection cache allows you to avoid the overhead of establishing a new connection every time a script needs to talk to a database, resulting in a faster web application.


1 Answers

$DBH = new PDO(     "mysql:host=$host;dbname=$dbname",      $username,      $password,     array(         PDO::ATTR_TIMEOUT => 5, // in seconds         PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION     ) ); 
like image 156
Shinto Joseph Avatar answered Sep 20 '22 20:09

Shinto Joseph