What is wrong, when you connect to the DB on the LINE BEFORE THE QUERY, and you still get "MySQL server has gone away"?
check this example code:
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 server is gone away, i get that in the foreach loop.
BTW i need to connect in the foreachloop, because it may take along time before it finds something to update (like 1-2 minutes), and then for sure i will get mysql server has gone away.
解决方案
I assume your issue is that the script may execute for a very long time before sending the first UPDATE query.
You should check the wait_timeout value in my.cnf. You can check your wait_timeout by running the query "SHOW VARIABLES;"
You can also try to piece of code to do a reconnect:
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);
}
Combining with your code it would be:
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'");
}
}