dqbr37828 2012-06-14 14:17
浏览 13
已采纳

使用PDO在2个不同数据库中重复行

I am using PDO (mysql) to create 2 different database connections. I want to transfer a row of data from 1 table to another in a different database. This is not a duplication of the row, only certain rows are selected.

I am unable to get it to work, any ideas?

  private function moveCallToProduction() {
    try {
        $sql = "SELECT * FROM `calls` WHERE `id`=':id'";
        $query = $this->staging->prepare($sql);
        $query->execute($array);
        $results = $query->fetchAll(PDO::FETCH_ASSOC);
        try {
            $sql = "INSERT INTO `calls` (`id`,`sip_id`,`extension`,`caller_id`,`stage`,`status`,`survey_id`,`start`,`answer`,`hangup`,`end`) VALUES ('?','?','?','?','?','?','?','?','?','?','?')";
            $query = $this->production->prepare($sql);
            $query->execute($results);
        }
        catch(PDOException $e) {
            $this->informer("FATAL","There was a problem");
        }

    }
    catch(PDOException $e) {
        $this->informer("FATAL","We're unable to transport the call from the staging to production server. Error: ".$e->getMessage());
    }
}
  • 写回答

1条回答 默认 最新

  • dongping4273 2012-06-14 14:49
    关注

    fetchAll() returns an array containing all of the result set rows. You need to iterate over each row and insert it individually. For example:

    ...
    $sql = "SELECT * FROM `calls` WHERE `id`=':id'";
    $query = $this->staging->prepare($sql);
    $query->execute($array);
    $results = $query->fetchAll(PDO::FETCH_ASSOC);
    foreach($results as $row) {
        try {
            $sql = "INSERT INTO `calls` (`id`,`sip_id`,`extension`,`caller_id`,`stage`,`status`,`survey_id`,`start`,`answer`,`hangup`,`end`) VALUES ('?','?','?','?','?','?','?','?','?','?','?')";
            $query = $this->production->prepare($sql);
            $query->execute($row);
        }
        catch(PDOException $e) {
            $this->informer("FATAL","There was a problem");
        }
    }
    ...
    

    You can also use the statement: while($result = $query->fetch(PDO::FETCH_ASSOC)) instead of fetchAll() to iterate over the results without having to store them in memory.

    One thing to consider is what you want to do if an exception is encountered. Since you're inserting many times, you might consider using PDO::beginTransation() at the beginning, PDO::commit() if no exceptions occur, and PDO::rollBack() to cancel any changes if an exception does occur. This way you can be sure that everything transfers or nothing does.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 hexo+github部署博客
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?