php mysqli可以在尝试连接时设置超时吗?

问题描述:

我已经把这行连接到mysql db了,只是想知道是否有一种方法可以设置连接尝试的超时时间?谢谢.

Hi I've this line to connect to mysql db and just wonder if there's a way to set a timeout for connect attempt? Thanks.

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

是的,您可以明确指定一个超时,以尝试使用mysqli从php程序连接到MySQL数据库.

Yes, you can specify a timeout explicitly for an attempt to connect from your php program to a MySQL database using mysqli.

虽然有点毛.使用new mysqli()时,将使用可重复使用的连接池.如果要设置超时或任何其他选项,则需要使用real_connect代替,如下所示:

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 );

这里有一个不错的解释: http://php.net/manual /en/mysqli.real-connect.php

There's a decent explanation here: http://php.net/manual/en/mysqli.real-connect.php