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

发布于 2024-11-27 22:14:23 字数 924 浏览 8 评论 0原文

我根据 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。 如果我在 Toad for MySQL 中尝试 SELECT LAST_INSERT_ID(),我确实得到了结果,但它不是最后插入行的 ID。

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

I'm inserting multiple rows from one table to another, based on ID.
For this project I'm using PDO for all DB queries. 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.
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.

Why isn't the last inserted row id registered when I insert rows this way?
Is it because I'm using beginTransaction and commit and therefore it is handled as one transaction?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

想挽留 2024-12-04 22:14:23

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

Yes, it is. You need to get the ID before you commit the transaction.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文