"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How can I Set a Connection Timeout with PDO?

How can I Set a Connection Timeout with PDO?

Published on 2024-11-18
Browse:998

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:

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

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3