Setting a Connect Timeout with Pdo

Setting a connect timeout with PDO

$DBH = new PDO(
"mysql:host=$host;dbname=$dbname",
$username,
$password,
array(
PDO::ATTR_TIMEOUT => 5, // in seconds
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
)
);

PDO sqlsrv database connection timeout

Try this (http://php.net/manual/de/ref.pdo-sqlsrv.connection.php):

$pdo = new \PDO("sqlsrv:Server=server;Database=dbname;LoginTimeout=5", 'username', 'password');

or this (https://technet.microsoft.com/en-us/library/ff628164(v=sql.105).aspx):

$pdo->setAttribute(\PDO::SQLSRV_ATTR_QUERY_TIMEOUT, 5);

But second solutions should work for normal query only. Hopefully, one of these solutions will help you.

Setting PDO connection timeout time less than 1 second

This is not possible because the underlying MySQL driver won't allow it:

Request #60716: Ability to set PDO connection timeout in milliseconds

PDO: Connection timed out when database is offline

You could set the timeout attribute:

private function initDb() {
if($this->db == NULL) {
try {
$this->db = new PDO('mysql:port='.$this->port.';host='.$this->host, $this->user, $this->password);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$this->db->setAttribute(PDO::ATTR_TIMEOUT, 5); //Add this.
}
catch (PDOException $error) {
echo '<b>An error occured!</b><br />' . $error->getMessage();
exit();
}
}
}

This would make the query time out after 5 seconds instead of the 30 seconds you describe in your question. Please note that the underlying mysql engine has to support this as not all support it.



Related Topics



Leave a reply



Submit