When connecting to a database using PHP Data Objects (PDO), experiencing extended delays in obtaining an exception if the server is unavailable can be frustrating. This issue typically arises before the PDO::setAttribute() method can be utilized.
To establish a connection timeout, an alternative approach is available. By passing an array of options to the PDO constructor, it's possible to set various connection attributes, including the timeout duration. An example of such a configuration is provided below:
<code class="php">$DBH = new PDO( "mysql:host=$host;dbname=$dbname", $username, $password, [ PDO::ATTR_TIMEOUT => 5, // in seconds PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ] );</code>
In this example, the connection timeout is set to 5 seconds with the PDO::ATTR_TIMEOUT option. When connecting to the database, if the connection attempt exceeds this duration, an exception will be promptly thrown, providing immediate feedback regarding the server's availability.
The above is the detailed content of How can I Set a Connection Timeout with PDO?. For more information, please follow other related articles on the PHP Chinese website!