简体   繁体   English

无法从MySQL获取最后插入的ID

[英]Not able to get last inserted ID from MySQL

I'm inserting multiple rows from one table to another, based on ID. 我根据ID在一个表中插入多行到另一个表。 For this project I'm using PDO for all DB queries. 对于这个项目,我正在使用PDO进行所有数据库查询。 This is the code / function I'm using: 这是我正在使用的代码/功能:

  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;
  }

But for some resaon, I'm not able to get the last inserted ID. 但是对于某些原因,我无法获得最后插入的ID。 If I try SELECT LAST_INSERT_ID() in Toad for MySQL , I do get a result, but it's not the ID of the last inserted row. 如果我在Toad for MySQL尝试SELECT LAST_INSERT_ID() ,我会得到一个结果,但它不是最后插入行的ID。

Why isn't the last inserted row id registered when I insert rows this way? 当我以这种方式插入行时,为什么没有注册最后插入的行id?
Is it because I'm using beginTransaction and commit and therefore it is handled as one transaction? 是因为我正在使用beginTransactioncommit ,因此它作为一个事务处理?

Yes, it is. 是的。 You need to get the ID before you commit the transaction. 您需要在提交事务之前获取ID。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM