Customizing Connect Timeouts with PDO
When accessing data from a MySQL server using PDO, a long wait time can be encountered before an exception is thrown when the server is unavailable. To address this issue, a timeout for connecting to the database can be specified.
To set a connect timeout, use the PDO::ATTR_TIMEOUT attribute when creating the PDO instance. This attribute specifies the number of seconds to wait before timing out a connection attempt.
<code class="php">$DBH = new PDO( "mysql:host=$host;dbname=$dbname", $username, $password, array( PDO::ATTR_TIMEOUT => 5, // in seconds PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ) );</code>
In this example, a timeout of 5 seconds is set. If the connection attempt takes longer than 5 seconds, a PDOException will be thrown.
It's important to note that this attribute affects only the initial connection attempt. Once the connection is established, subsequent queries will not be affected by this timeout.
The above is the detailed content of How do I customize Connect Timeouts with PDO?. For more information, please follow other related articles on the PHP Chinese website!