PHP的mysqli重新连接问题(PHP mysqli reconnect problem)

2019-08-16 17:58发布

I am having trouble using the mysqli class in PHP and I haven't been able to find the answer anywhere.

In my script a class creates a mysqli connection that it uses throughout it's functions. Afterward, this script forks. The connection is used by the children as well, but I'm running into the problem of the connection being closed (MYSQL Server Has Gone Away) in the parent when the children die.

Before I switched to mysqli (was just using mysql) I simply called mysql_ping to assure that the db connection was there before performing the query in the parent process. Mysqli has a similar ping function BUT it doesn't actually reconnect if the connection is gone. I tried using the mysqli.reconnect=ON global setting with no luck (using php.ini and ini_set).

The php mysql_connect function allows you to grab an already-existing connection, so if I was using mysql instead of mysqli, I could simply reuse the connection in the child right after the process forked. BUT mysqli doesn't seem to have any such functionality...

The only thing I was able to do was call mysqli->ping() and if that returned false then reconnect to the database in the parent. This is terribly inefficient, and I would much rather figure out how to do it correctly with mysqli (and no need for manual reconnects) that having to change back to mysql..

Any suggestions?

Answer 1:

对于DOC mysqli_ping()说,如果你设置的全局选项mysqli.reconnect为1(在php.ini)然后mysqli_ping()会在检测到连接已经消失重新连接。

更新:自2009年,我回答了这个问题,PHP大多移动在默认情况下,而不是的libmysql使用mysqlnd驱动程序。 正如在下面的评论中提到,mysqlnd不支持mysqli_ping()函数,和PHP开发人员故意这样做,根据他们“不会解决”在回答https://bugs.php.net/bug.php? ID = 52561

因此,有似乎是在PHP自动重新连接无解了。



Answer 2:

ü可以尝试一些有点不同..不是..坪尝试发送一个非常简单的低强度的查询,如“选择现在()”,看看你得到任何更好的结果。



Answer 3:

你不能使用永久连接? 而且,是真的有必要fork()的?



Answer 4:

function IsConnected() {
    if (empty($this->_connectionID) === FALSE && mysqli_ping($this->_connectionID) === TRUE) {
        return true; // still have connect
    }
    $this->_connectionID = false;
    return false; // lose connection
}


Answer 5:

使用http://www.php.net/manual/en/mysqli.real-connect.php ...重新安装PHP和检查您的php.ini设置



Answer 6:

我认为你需要设置my.cng mysqli.reconnect,这是MySQL的配置,而不是php.ini中,我不能设法改变通过的ini_set重新连接,但我的系统管理员做到了在my.cnf。

所以,点点困惑,其他人已经php.ini文件中做了....



文章来源: PHP mysqli reconnect problem