2

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.

2
  • 1
    Have you tried mysqli_insert_id ? Commented Oct 11, 2010 at 1:16
  • Returns the last id only not all Commented Oct 11, 2010 at 1:17

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.