Reputation: 2489
I've this line to connect to MySQL db and just wonder if there's a way to set a timeout for connect attempt?
$db = new mysqli($server, $usr, $passwd, $dbname);
Upvotes: 6
Views: 19424
Reputation: 108641
Yes, you can specify a timeout explicitly for an attempt to connect from your php program to a MySQL database using mysqli.
It's a little hairy, though. If you want to set a timeout, or any other option, you need to use real_connect
instead of new mysqli
, like the following:
$timeout = 30; /* thirty seconds for timeout */
$link = mysqli_init( );
$link->options( MYSQLI_OPT_CONNECT_TIMEOUT, $timeout );
$link->real_connect($server, $usr, $passwd, $dbname);
There's a decent explanation here: https://php.net/manual/en/mysqli.real-connect.php
Upvotes: 19