tags:

views:

27

answers:

1

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.

A: 

If you can't, you can have a new column created which is DATETIME. Simply set its value to NOW().

Then you can get the last inserted rows by doing

SELECT MAX(`created`) AS `last_inserted_id`
  FROM `your_table` 

Of course, MAX(id) will probably also work, but it is a bit hacky, and I do not recommend doing it that way.

Update

If you wanted the last 3 inserted rows, something like this would work.

  SELECT `id`
    FROM `your_table`
ORDER BY `created` DESC
   LIMIT 3
alex
Would not this return the values of the column created instead of the ids
It will return the `id` of the row with the newest `created` column.
alex
@alex: this will return unexpected results if 2 scripts worked simultaneously.
zerkms
@zerkms What would be a better way? Thanks.
alex
I'm not sure there is way at all, but this solution is completely wrong, since it can return wrong data.
zerkms
@zerkms Well if you want the latest rows added based on a datetime, it will work.
alex
1. I bet he wants to get id's of just inserted records by **current script**. 2. You could change `order by` clause to `ORDER BY id DESC` due to it will be more performant.
zerkms
@zerkms I guess I would want much more information to answer this question.
alex
We all need more information, indeed ;-) But if he wants to get the **current** ids, then it is not possible in case of multiquery.
zerkms
@zerkms We'll see what he ends up doing...
alex
I managed to get it work by adding SELECT LAST_INSERT_ID(); after each INSERT query in the multi query and then use the mysql use result to get all ids, and I think this is the best way.