PHP MySQLi从multi_query()插入ID [英] PHP MySQLi insert ids from multi_query()

查看:70
本文介绍了PHP MySQLi从multi_query()插入ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用mysqli multi_query函数插入几行后,是否有办法获取最后生成的auto_increment ID?

Is there a way to get the last generated auto_increment IDs after inserting several rows with mysqli multi_query function?

我设法通过添加SELECT LAST_INSERT_ID()使其工作.在多查询中的每个INSERT查询之后,然后使用mysqli_use_result获取所有ID,我认为这是最好的方法.

I managed to get it work by adding SELECT LAST_INSERT_ID(); after each INSERT query in the multi query and then use the mysqli_use_result to get all ids, and I think this is the best way.

推荐答案

您可以通过为每个连续的插入语句调用MySQLi的next_result()来获取不同的插入ID.据我所知,只要查询是插入语句或其他不返回结果集的内容,您就不必存储任何结果.

You can fetch the different insert ids by calling MySQLi's next_result() for each consecutive insert statement. As far as I know, you don't have to store any results as long as the queries are insert statements or something else that doesn't return a result set.

$sql = new MySQLi("...");
$query = "INSERT STATEMENT NUMBER ONE;";
$query .= "INSERT STATEMENT NUMBER TWO;";
$query .= "INSERT STATEMENT NUMBER THREE";
$sql->multi_query($query);

// The first insert id will be available at once
$id1 = $sql->insert_id;

// The second needs to be handeled a little differently
$sql->next_result();
$id2 = $sql->insert_id;

// And lastly the third one
$sql->next_result();
$id3 = $sql->insert_id;

如果不确定有多少个插入语句,也可以将其循环放置:

You can also put this in a loop if you are unsure of how many insert statements there are:

$ids = array();
do
{
    $ids[] = $sql->insert_id;
    $sql->next_result();
} while($sql->more_results());

这是未经测试的伪代码(您可能已经猜到过),但是应该可以使用.

This is untested pseudo code (as you might have figured), but it should work.

这篇关于PHP MySQLi从multi_query()插入ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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