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
Pass Array Literal to Postgresql Function
Using Simplexml to Load Remote Url
Transfer Variables Between PHP Pages
PHP Try-Catch Blocks: Are They Able to Catch Invalid Arg Types
PHP Method Argument Type Hinting with Question Mark (Type)
How to Bind an Arbitrary Number of Values to a Prepared Statement in MySQLi
Passing Variables from PHP to JavaScript
Hunting Cheaters in a Voting Competition
How to Access an Object Property Named as a Variable in PHP
How to Validate a Domain Name Using Regex & PHP
File_Exists() Returns False Even If File Exist (Remote Url)
How to Run a .Sh File from PHP
JavaScript Function Post and Call PHP Script
Array_Map Function in PHP with Parameter