无法从 MySQL 获取最后插入的 ID
我根据 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 没有注册?
是否因为我正在使用 beginTransaction
和 commit
因此它被作为一个事务处理?
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的。您需要在提交交易之前获取 ID。
Yes, it is. You need to get the ID before you commit the transaction.