Home >Database >Mysql Tutorial >How can I Set a Connection Timeout with PDO?

How can I Set a Connection Timeout with PDO?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-04 02:01:30851browse

How can I Set a Connection Timeout with PDO?

Setting a Connection Timeout with PDO: A Comprehensive Guide

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!

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