2011-09-02 104 views
2

什麼是錯誤的,當你在QUERY上連接到線路上的數據庫時,你仍然得到「MySQL服務器已經消失」?php,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服務器已經消失。

+0

是使用相同的MySQL服務器和架構兩個MySQL連接? – opps

+2

我不認爲你應該連接到整個腳本的數據庫不止一次。 –

+0

你如何得到你的foreach循環中的連接已經消失?這個腳本的輸出是什麼(錯誤信息)? – Rijk

回答

6

我假設你的問題是在發送第一個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'"); 
    } 
} 
+1

同樣的事情發生:(MySQL服務器已經消失 –

+0

另外,我只是意識到,沒有必要循環兩次? –

+0

嘗試修改版本嗎?另外,也許你的「file_get_contents」是非常慢? –

0

這周我們得到了錯誤,在這裏工作是從MySQL的官方文檔:http://dev.mysql.com/doc/refman/5.0/en/gone-away.html

這部分還包括查詢錯誤期間服務器相關的連接丟失。

MySQL服務器最常見的原因已消失錯誤是服務器超時並關閉連接。