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

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

问题描述

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

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,以任何方式获取2个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天全站免登陆