PHP MySQLi insert ids from multi_query()

2019-03-01 02:30发布

问题:

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

EDIT:

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.

回答1:

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