利用PHP脚本辅助MySQL数据库管理4-两个库表结构差异比较

<?php
define('DATABASE1', 'coffeetest');
$dbi1 = new DbMysql;
$dbi1->dbh = 'mysql://root:[email protected]/'.DATABASE1;

define('DATABASE2', 'sinatest');
$dbi2 = new DbMysql;
$dbi2->dbh = 'mysql://root:[email protected]/'.DATABASE2;


// db1
$db1 = array();
$map = array();
$dbi1->fetchMap("SHOW TABLES", $map);
$tables = array_keys($map);
for($i=0; $i<count($tables); $i++){
    $map = array();
    $dbi1->fetchMap("DESCRIBE ".$tables[$i], $map);
    $structures = array();
    foreach($map as $k=>$v){
        $structures[] = "$k=$v";
    }
    $db1[$tables[$i]] = $structures;
}

// db2
$db2 = array();
$map = array();
$dbi2->fetchMap("SHOW TABLES", $map);
$tables = array_keys($map);
for($i=0; $i<count($tables); $i++){
    $map = array();
    $dbi2->fetchMap("DESCRIBE ".$tables[$i], $map);
    $structures = array();
    foreach($map as $k=>$v){
        $structures[] = "$k=$v";
    }
    $db2[$tables[$i]] = $structures;
}

// db1 compare db2
echo("***** ".DATABASE1." *****\n");
foreach($db2 as $table=>$structures2){
    $structures1 = $db1[$table];
    if(empty($structures1)) {
        echo(".$table not exist\n");
        continue;
    }
    for($i=0; $i<count($structures2); $i++){
        if(1==1 && !in_array($structures2[$i], $structures1))
            echo $table.".".$structures2[$i]."\n";
    }
}

// db2 compare db1
echo("***** ".DATABASE2." *****\n");
foreach($db1 as $table=>$structures1){
    $structures2 = $db2[$table];
    if(empty($structures2)) {
        echo(DATABASE2.".$table not exist\n");
        continue;
    }
    for($i=0; $i<count($structures1); $i++){
        if(1==0 && !in_array($structures1[$i], $structures2))
            echo $table.".".$structures1[$i]."\n";
    }
}
?>

猜你喜欢

转载自www.cnblogs.com/coffee_cn/p/8994343.html