简体   繁体   English

PHP MySQLi从multi_query()插入id

[英]PHP MySQLi insert ids from multi_query()

Is there a way to get the last generated auto_increment IDs after inserting several rows with mysqli multi_query function? 在使用mysqli multi_query函数插入多行后,有没有办法获取最后生成的auto_increment ID?

EDIT: 编辑:

I managed to get it work by adding SELECT LAST_INSERT_ID(); 我设法通过添加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. 在多查询中的每个INSERT查询之后,然后使用mysqli_use_result来获取所有ID,我认为这是最好的方法。

You can fetch the different insert ids by calling MySQLi's next_result() for each consecutive insert statement. 您可以通过为每个连续的insert语句调用MySQLi的next_result()来获取不同的insert id。 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: 如果您不确定有多少个insert语句,也可以将它放在循环中:

$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. 这是未经测试的伪代码(正如您可能已经想到的那样),但它应该可以工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM