我可以构建一个php页面来对30个mysql数据库运行查询检查吗?

rfbsl7qr  于 2023-05-16  发布在  PHP
关注(0)|答案(2)|浏览(68)

我在hostgator托管,有大约30个mysql数据库(所有不同的网站都位于同一台服务器上)。在过去的一年里。没有问题,突然,在过去的2天里,我看到5 - 10个这些数据库被标记为“崩溃”,他们没有返回任何结果…所以我的网站没有显示任何信息。我必须运行一个“修复表mytable”来修复这些,然后它们再次工作得很好。
与其每天早上一个接一个地登录数据库,有没有一种方法可以让我设置一个php页面来连接所有30个数据库并运行一个简单的select语句。如果它工作,则返回“数据库db 1正在工作”“数据库db2正在工作”,然后当它不工作时,返回“没有来自db 3的应答”
或者类似的东西?
谢谢!

afdcj2ne

afdcj2ne1#

没有理由你不能有一个脚本,列出所有的数据库名称和登录凭据,并尝试依次连接到每个:

$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);
}
bzzcjhmw

bzzcjhmw2#

您应该能够执行以下操作:

<?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].";");
            }
        }
    }
?>

相关问题