I'm currently using $mysqli->insert_id
to retrieve auto-allocated primary keys from a MySQL table when new rows are inserted. This works fine on single inserts. It's a simple case of
$result = $mysqli->query($query);
$NewPrimaryKey = $mysqli->insert_id;
However, I've learned (from this site actually) that multiple inserts are better done with an extended insert:
insert into table (name1,name2,name3) values
('blah1','blah2',blah3'),
('blah1','blah2',blah3'),
('blah1','blah2',blah3'))
This also works great – except when I want to know what keys were auto-allocated.
The PHP manual says:
When running extended inserts on a table with an AUTO_INCREMENT field, the value of mysqli_insert_id() will equal the value of the first row inserted.
My testing appears to confirm this.
Note: I don't want just the first or just the last.
I don't want to have to revert to thousands of single inserts just so that I can get the auto_allocated key on an individual basis.
Does anyone know of a way to do extended inserts and to get back all the keys that were allocated (presumably in a array)?
It did occur to me to just read and retain the latest existing key before doing the extended write and then to calculate the expected values of the allocated keys, but this does seem a little bodgified.