复制MySQL中第二个数据库中第一个数据库的一列

时间:2015-12-07 20:43:53

标签: php mysql database

我用更新命令(大约18000条记录)错误地更改了所有一列数据库

我有备份,因此将其重新存储到另一个数据库名称

我想要的一切就是将备份数据库的一列复制到master数据库的库存中(更新) 所以我在php中编写这段代码:

ini_set('max_execution_time', 3000000000000000000000000000000000000000000);
error_reporting(E_ALL);
ini_set('display_errors', 1);

function connection1()
{
    $DBName1 = "db1";
    $DBUser1 = "user1";
    $DBPassword1 = "pass1";
    $DBHost1 = "localhost";


    try {
        $pdo = new PDO("mysql:host=" . $DBHost1 . ";dbname=" . $DBName1 .
            ";charset=utf8", $DBUser1, $DBPassword1, array(
            PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'",
            PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_ERRMODE));
        return $pdo;
    }
    catch (PDOException $e) {
        echo "Failed to get DB handle: " . $e->getMessage() . "\n";
        exit;
    }
}

function connection2()
{
    $DBName2 = "db2";
    $DBUser2 = "user2";
    $DBPassword2 = "pass2";
    $DBHost2 = "localhost";


    try {
        $pdo = new PDO("mysql:host=" . $DBHost2 . ";dbname=" . $DBName2 .
            ";charset=utf8", $DBUser2, $DBPassword2, array(
            PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'",
            PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_ERRMODE));
        return $pdo;
    }
    catch (PDOException $e) {
        echo "Failed to get DB handle: " . $e->getMessage() . "\n";
        exit;
    }
}


$con2 = connection2();
$NewItem = $con2->prepare("select id,fid,title,sign from news_tmp");
$NewItem->execute();

$con1 = connection1();
$contwovalue = array();

for ($i = 0; $row = $NewItem->fetch(PDO::FETCH_ASSOC); $i++) {
    $NewItem2 = $con1->prepare("select id,fid,title,sign from news_tmp where id='{$row['id']}'");
    $NewItem2->execute();
    $contwovalue = $NewItem2->fetch(PDO::FETCH_ASSOC);
    if (($contwovalue['id'] == $row['id']) && ($contwovalue['fid'] == $row['fid']) &&
        ($contwovalue['sign'] == $row['sign'])) {
        $NewItem2 = $con1->prepare("UPDATE `news_tmp` SET `title`=? where id=?");
        $NewItem2->bindValue(1, $row['title'], PDO::PARAM_INT);
        $NewItem2->bindValue(2, $contwovalue['id'], PDO::PARAM_INT);
        $NewItem2->execute();
    }
}

我只是想问这个问题:这种方式是最好的方法吗?还是存在这个问题的另一种方式?

1 个答案:

答案 0 :(得分:0)

为什么不直接使用查询呢?

UPDATE 
  database.news
SET 
  database.news.title= backupdatabase.news.title
WHERE 
  database.news.id= backupdatabase.news.id

编辑:哦,大约6个月后: - )