2011-10-22 43 views
3

我在hostgator上託管並擁有大約30個mysql數據庫(位於同一服務器上的所有不同網站)。在去年...沒有問題,突然,過去2天,我看到這些數據庫中有5 - 10個被標記爲'崩潰',並且他們沒有返回結果...所以我的網站不顯示任何信息。我必須運行「修復表mytable」來修復這些問題,然後再次運行。我可以構建一個php頁面來針對30個mysql數據庫運行查詢檢查嗎?

而不是每天早上登錄一遍一遍地查看數據庫,有沒有一種方法可以設置一個php頁面來連接到所有30個數據庫並運行一個簡單的選擇語句..如果它工作,返回 「數據庫DB1工作」 「數據庫DB2正在」 然後不工作時,「從DB3未回覆」退回

....或者類似的東西?

謝謝!

回答

4

沒有理由你不能有一個腳本,列出了所有你databasenames和登錄憑據,並嘗試依次連接到每個:

$logins = array(
    array('dbname' => 'blah', 'user' => 'username1', 'password' => 'password1'), 
    array('dbname' => 'yuck', ....) 
    ... 
); 

$failures = array(); 

foreach ($logins as $login) { 
    $con = mysql_connect('servername', $login['user'], $login['password']); 
    if (!$con) { 
     $failures[] = $login['dbname'] . " failed with " . mysql_error(); 
     continue; 
    } 
    $result = mysql_select_db($login['dbname']); 
    if (!$result) { 
     $failures[] = "Failed to select " . $login['dbname'] . ": " . mysql_error(); 
     continue; 
    } 
    $result = mysql_query("SELECT something FROM sometable"); 
    if (!$result) { 
     $failures[] = "Faile to select from " . $login['dbname'] . ": " . mysql_error(); 
     continue; 
    } 
    if (mysql_num_rows($result) != $some_expected_value) { 
     $failures[] = "Got incorrect rowcount " . mysql_num_rows($result) . " on " . $login['dbname']; 
    } 
    etc.... 
    mysql_close(); 
} 

if (count($failures) > 0) { 
    echo "Failures found: " 
    print_r($failures); 
} 
+0

完美。非常感謝你! – Andi

+0

我剛剛在警報中添加了域名,並在將servername更新到localhost併爲$ some_expected_value提供了一個值之後,這可能無法正常工作。這麼好的解決方案如此之快!就像你在這裏所做的那樣,只寫錯誤就容易多了。我在想什麼? :) 再次感謝。太棒了! – Andi

0

你應該能夠做到像下面:

<?php 
//connect to database 
mysql_connect('database','user','password'); 

//get all database names 
$result = mysql_query("show databases;"); 

//iterate over all databases returned from 'show databases' query 
while($row = mysql_fetch_array($result)) { 
    //DB name is returned in the result set's first element. select that DB 
    mysql_selectdb($row[0]); 
    //get all tables in the database 
    $query = "show tables;"; 
    $result2 = mysql_query($query); 
    echo "Query: (".$row[0].")$query\n"; 
    echo mysql_error(); 
    //iterate over all tables in the current database 
    while($row2 = mysql_fetch_array($result2)) { 
      //the first element of the returned array will always be the table name, so: 
      $query = "select * from ".$row2[0]." where 1=1;"; 
      $result3 = mysql_query($query); 
      echo "Query:\t(".$row[0].'/'.$row2[0].")$query\n"; 
      //If mysql_query returns false (i.e., $result3 is false), that means that 
      // the table is damaged 
      if(!$result3) { 
        echo "***Error on table '".$row2[0]."' *** ... Fixing..."; 
        //So, we repair the table 
        mysql_query("repair table ".$row2[0].";"); 
      } 
     } 
    } 
?> 
相關問題