Single

PHP修复MySQL所有数据库中的表

项目中总是存在各种各样的情形导致MySQL中的表被损坏,此时为确保程序的正确执行和数据的完整性,需对表进行修复,思路大致如下:

1.使用PHP连接MySQL

2.列出MySQL中的所有数据库名称

3.列出每个数据库中的所有表名

4.分别对各个表进行修复

一个包含以上四个功能的PHP类如下:

<?php
class MySQLTool{
 public static $con="";
 public static function getConnect($host, $user, $psw, $charset="utf8"){
 if(self::$con=="" || !is_resource(self::$con) ){
 self::$con=mysql_connect($host, $user, $psw);
 mysql_query("set names ".$charset,self::$con);
 }
 return self::$con;
 }
 public static function closeConnect(){
 if(self::$con!=""){
 mysql_close(self::$con);
 self::$con="";
 }
 }
 /*获取所有的数据库名称*/
 public static function getAllDatabases(){
 $db_list = mysql_list_dbs(self::$con);
 $databases = array();
 while ($row = mysql_fetch_object($db_list)) {
 $databases[] = $row->Database;
 }
 return $databases;
 }
 /*获取每个数据库中的所有表*/
 public static function getAllTables($dbname) {
 $result = mysql_list_tables($dbname);
 $tables = array();
 while ($row = mysql_fetch_row($result)) {
 $tables[] = $row[0];
 }
 mysql_free_result($result);
 return $tables;
 }
 /*修复一个数据库*/
 public static function repairDatabase($dbname){
 mysql_select_db($dbname, self::$con);
 $tables = self::getAllTables($dbname);
 $len = count($tables);
 for($i = 0; $i < $len; $i++){
 $tbname = $tables[$i];
 $sql = "repair table ".$tbname;
 $result = mysql_query($sql);
 if($result){
 echo "repair table [$tbname] in database [$dbname] is successful!\n";
 } else {
 echo "repair table [$tbname] in database [$dbname] is failed!\n";
 }
 }
 }
 /*修复所有的数据库*/
 public static function repairAllDatabase(){
 $databases = self::getAllDatabases();
 $len = count($databases);
 for($i = 0; $i < $len; $i++){
 $dbname = $databases[$i];
 self::repairDatabase($dbname);
 }
 }
 
}
?>

暂无评论

发表评论