本文介绍了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

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

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

08-26 09:39
查看更多