2011-10-22 38 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].";"); 
      } 
     } 
    } 
?> 
相关问题