Home  >  Article  >  Database  >  How to Set a Connect Timeout for PDO?

How to Set a Connect Timeout for PDO?

Barbara Streisand
Barbara StreisandOriginal
2024-11-03 19:55:03514browse

How to Set a Connect Timeout for PDO?

Setting a Connect Timeout with PDO

When using PDO to retrieve data from a MySQL server, you may encounter lengthy delays when the server is inaccessible. By default, PDO takes over 2 minutes to throw an exception in the case of MySQL and 30 seconds for PostgreSQL, which can be excessively long.

To alleviate this issue, you can set a timeout for connecting to the database using the following syntax:

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

By setting the PDO::ATTR_TIMEOUT attribute, you can specify the maximum time in seconds that PDO will wait before establishing a connection. In the example above, the connection attempt will time out after 5 seconds.

It's important to note that setting a connect timeout does not guarantee instant failover. If the server comes back online before the timeout expires, PDO will successfully establish the connection. However, it does provide a more responsive approach to handling connection issues, reducing the time your application spends waiting for an unavailable server.

The above is the detailed content of How to Set a Connect Timeout for PDO?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn