I'm writing a plugin where I need to save data in custom tables, function hits an API and then saves data for which I need bulk insert, but as wpdb doesn't support it out of the box I made a function for it using prepare and query.

But query doesn't return inserted row IDs. How can I get them? Any other way or anything besides using wpdb?

1 Answer 1


As described here:

If you insert multiple rows using a single INSERT statement, LAST_INSERT_ID() returns the value generated for the first inserted row only. The reason for this is to make it possible to reproduce easily the same INSERT statement against some other server.

So if you need every inserted ID you should use single $wpdb->insert commands, then you have the ID available for each with $wpdb->insert_id. Docs here: https://codex.wordpress.org/Function_Reference/wpdb_Class#INSERT_row

If you insert many rows with a single query you can't get all the inserted ID's, unless you e.g. wanted to re-query for them if you are sure you can identify those rows uniquely.

  • yes, I know that already, thing is single inserts impact database more as opposed to bulk inserts, and I will have multiple tables with datasets to insert so I can't rely on that, as it might break.
    – ateebahmed
    Jun 15, 2020 at 11:24
  • @ateebahmed you can't have it both ways ;-) so if you want to do a bulk insert then you need to SELECT again to find the ID's
    – mozboz
    Jun 15, 2020 at 11:34
  • yeah thanks, I'm doing it already, wanted to know if I can somehow bypass wpdb itself and call the underlying db class or if php provide any way to get all ids in an array
    – ateebahmed
    Jun 15, 2020 at 12:10

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.