Can php mysqli set a timeout when trying to connect?

Hi I have this line for connecting to mysql db and just wondering if there is a way to set a timeout for a connection attempt? Thank.

$db = new mysqli($server, $usr, $passwd, $dbname);

      

+4


source to share


1 answer


Yes, you can explicitly timeout for trying to connect from your php program to MySQL database using mysqli.

It's a little hairy though. When you use new mysqli()

you are using a pool of reused connections. If you want to set timeout or any other parameter, you need to use instead real_connect

like real_connect

below:



$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: http://php.net/manual/en/mysqli.real-connect.php

+11


source







All Articles