Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can PHP mysqli set timeout on connect attempt?

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);
like image 854
sparkmix Avatar asked Nov 06 '14 16:11

sparkmix


1 Answers

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

like image 104
O. Jones Avatar answered Sep 17 '22 23:09

O. Jones