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);
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. When you use new mysqli()
you use a pool of reusable connections. If you want to set a timeout, or any other option, you need to use real_connect
instead, like the following:
$timeout = 30; /* thirty seconds for timeout */
$link = mysqli_init( );
$link->options( MYSQLI_OPT_CONNECT_TIMEOUT, $timeout ) ||
die( 'mysqli_options croaked: ' . $link->error );
$link->real_connect($server, $usr, $passwd, $dbname) ||
die( 'mysqli_real_connect croaked: ' . $link->error );
There's a decent explanation here: https://php.net/manual/en/mysqli.real-connect.php
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With