PDO - lastInsertId() 用于插入多行查询 [英] PDO - lastInsertId() for insert query with multiple rows

查看:34
本文介绍了PDO - lastInsertId() 用于插入多行查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以将 2 个宠物插入一个表,并获取它们的 lastInsertId() 以一次进一步处理一个(2 个查询).
我想知道如果我在 1 个查询中插入 2 行,是否有办法获取两个 lastInsertIds() 并将它们分配给变量:

I can insert 2 pets into a table, and get their lastInsertId() for further processing one at a time (2 queries).
I am wondering if there is a way to get two lastInsertIds() and assign them to variables if I am inserting 2 rows in 1 query:

$query = "INSERT INTO pets (pet_name) VALUES (':coco'),(':jojo')";
$pet_insert = $dbh->prepare($query);
$pet_insert->execute(array(':coco' => $coco,':jojo' => $jojo));
$New_PetID = $dbh->lastInsertId();

是否可以为 coco 和 jojo 获取 lastInsertId()?所以像:

Is it possible to get the lastInsertId() for coco and for jojo? So something like:

$New_PetID1 = $dbh->lastInsertId();//coco
$New_PetID2 = $dbh->lastInsertId();//jojo

这将给出相同的 ID,有什么办法可以得到这两个 ID?仅供参考,这是在 try 块中.

This will give the same ID, any way to get the 2 IDs? Just for reference, this is in a try block.

推荐答案

这是不可能的.如果您需要为两行生成 ID - 您需要执行 2 个分隔的 INSERT

It's not possible. If you need generated ids for both rows - you need to perform 2 separated INSERT

重要如果您使用单个 INSERT 语句插入多行,LAST_INSERT_ID() 返回为 第一次插入生成的值仅行.这样做的原因是为了可以复制很容易对其他服务器执行相同的 INSERT 语句.

Important If you insert multiple rows using a single INSERT statement, LAST_INSERT_ID() returns the value generated for the first inserted row only. The reason for this is to make it possible to reproduce easily the same INSERT statement against some other server.

http://dev.mysql.com/doc/refman/5.5/en/information-functions.html#function_last-insert-id

这篇关于PDO - lastInsertId() 用于插入多行查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆