1

我根据 ID 将多行从一个表插入到另一个表。对于这个项目,我将 PDO 用于所有数据库查询。这是我正在使用的代码/功能:

  protected function importData($data) {
    $i = 0;

    $this->db->beginTransaction();

    foreach($data as $item) {
      $id = $item['id'];

      $sql .= "INSERT INTO table1 (name,age)
              SELECT name, age
              FROM table12
              WHERE id = $id; ";

      $this->db->exec($sql);   
      $i++;   
    }
    $this->db->commit();

    // None of these are working
    $last_id1 = $this->db->exec('SELECT LAST_INSERT_ID()');
    $last_id2 = $this->db->lastInsertId();

    echo 'id1: '.$last_id1.', id2:'.$last_id2;
  }

但出于某种原因,我无法获得最后插入的 ID。如果我尝试SELECT LAST_INSERT_ID()Toad for MySQL我会得到一个结果,但它不是最后插入的行的 ID。

当我以这种方式插入行时,为什么没有注册最后插入的行 ID?
是因为我正在使用beginTransactioncommit因此它被作为一笔交易处理吗?

4

1 回答 1

4

是的。您需要在提交事务之前获取 ID。

于 2011-08-03T09:11:43.760 回答