doqrt26664 2012-04-10 03:28
浏览 74
已采纳

Php PDO在事务中多个准备语句

I have this code:

    $this->db->beginTransaction();
    $query = 'INSERT INTO `table1` VALUES (NULL,:a,:b,NULL,NOW())';
    $sth = $this->db->prepare($query);
    foreach ($values as $k => $v) {
      $sth->bindParam(':' . $k, $v, PDO::PARAM_INT);
    }

    $this->executeQueryRollbackOnException($sth, 'Message_1');
    $resetId = $this->db->lastInsertId();

    $query = 'UPDATE `table2` SET c=:c,d=:d WHERE reset_id IS NULL';
    $sth = $this->db->prepare($query);
    foreach ($values2 as $k => $v) {
      $sth->bindParam(':' . $k, $v, PDO::PARAM_INT);
    }


    $this->executeQueryRollbackOnException($sth, 'Message_2');

    Zend_Debug::dump($sth->rowCount(), 'Affected'); // This is 0

    // Commit
    $this->db->commit();    

...

  private function executeQueryRollbackOnException($sth, $message) {
    try {
      $sth->execute();
    } catch (Exception $e) {
      $this->logSQLError($e);
      $this->db->rollBack();
      throw new Exception($message);
    }
  }

First query is executed but the second is not. No mysql error produced. Any ideas ?

展开全部

  • 写回答

2条回答 默认 最新

  • duanmu3049 2012-04-10 03:55
    关注

    I found the solution.

    foreach ($values as $k => $v) {
       $sth->bindParam(':' . $k, $v, PDO::PARAM_INT);
    }
    

    Should be

    foreach ($values as $k => $v) {
       $sth->bindParam(':' . $k, $values[$k], PDO::PARAM_INT);
    }
    

    Sorry I didn't posted the right code at first time, I excluded foreaches to simplify the code

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部