[英]php, mysql server has gone away
当您在查询之前在线连接到数据库时,仍然出现“ MySQL服务器已消失”的情况,这是怎么回事?
检查以下示例代码:
mysql_connect("localhost", "xxx", "xxx") or die(mysql_error());
mysql_select_db("xxx") or die(mysql_error());
$sql = mysql_query("SELECT id FROM db");
while ($data = mysql_fetch_assoc($sql)) {
$ids[] = $data[id];
}
foreach ($ids as $id) {
$content = file_get_contents("http://www.id.com/?id=$id");
if (stristr($content, "the id is ok man")) {
mysql_connect("localhost", "xxx", "xxx") or die(mysql_error());
mysql_select_db("xxx") or die(mysql_error());
mysql_query("UPDATE db SET status = 'OK' WHERE id = '$id'");
}
}
mysql服务器不见了,我在foreach循环中得到了它。 顺便说一句,我需要在foreachloop中进行连接,因为它可能需要一段时间才能找到要更新的内容(例如1-2分钟),然后确定我将使mysql服务器消失。
我认为您的问题是脚本在发送第一个UPDATE查询之前可能会执行很长时间。
您应该检查my.cnf中的wait_timeout值。 您可以通过运行查询“ SHOW VARIABLES;”来检查您的wait_timeout。
您也可以尝试编写一段代码来重新连接:
if (!mysql_ping ($conn)) {
//here is the major trick, you have to close the connection (even though its not currently working) for it to recreate properly.
mysql_close($conn);
$conn = mysql_connect('localhost','user','pass');
mysql_select_db('db',$conn);
}
结合您的代码将是:
mysql_connect("localhost", "xxx", "xxx") or die(mysql_error());
mysql_select_db("xxx") or die(mysql_error());
$sql = mysql_query("SELECT id FROM db");
while ($data = mysql_fetch_assoc($sql)) {
if (!mysql_ping ()) {
//here is the major trick, you have to close the connection (even though its not currently working) for it to recreate properly.
mysql_close();
mysql_connect("localhost", "xxx", "xxx") or die(mysql_error());
mysql_select_db("xxx") or die(mysql_error());
}
$ids[] = $data['id'];
$content = file_get_contents("http://www.id.com/?id=$id");
if (stristr($content, "the id is ok man")) {
mysql_query("UPDATE db SET status = 'OK' WHERE id = '$id'");
}
}
这个星期我们在工作时遇到了这个错误,这里是MySQL的官方文档: http : //dev.mysql.com/doc/refman/5.0/en/gone-away.html
本节还介绍了在查询错误期间与服务器的相关丢失连接。
MySQL服务器消失的最常见原因是服务器超时并关闭了连接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.