How retrieve in PHP the generated PRIMARY KEY from an AUTO_INCREMENT column for each row with an INSERT of multiple rows in MySQL?

StackOverflow https://stackoverflow.com/questions/15690866

Question

I have an INSERT with syntax for insert multiple rows:

INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);

With MySQL function LAST_INSERT_ID() can retrieve the primary key of an generated AUTO_INCREMENT column, but how can I retrieve the primary key for row (1,2,3), (4,5,6) AND (7,8,9) inserted in one unique SQL INSERT instruction?

The programming language is PHP 5.4.13 and MySQL Server 5.6.10

Was it helpful?

Solution

There is no way to retrieve more than one generated auto-inc variable. Calling LAST_INSERT_ID() returns you the first value generated by the last INSERT.

To get all the values, insert one row at a time, and call LAST_INSERT_ID() after each one. This results in more overhead, but it's the only workaround.

This is especially an issue if you're doing INSERT...SELECT or LOAD DATA INFILE, generating many new id values in a batch.

See also MySQL LAST_INSERT_ID() used with multiple records INSERT statement

OTHER TIPS

You can insert records in loop and when each record is inserted store the Auto increment id in array by call last_insert_id(). So you use the array of inserted id's where ever you need.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top