WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Is it safe to use $wpdb->insert_id; to find the id of a last updated row id just after an update? ex:

 $sql = $wpdb->insert($table_name, $arrayWithDataToInsert, array('%s','%s'));
            $results['new_created_id'] = $wpdb->insert_id;

or am I running into the possibility that I will catch the id of another row that was inserted immediatly after mine?


share|improve this question
up vote 4 down vote accepted

At a higher level, there truly isn't any means to know if the php/db connector will return the correct id by relying on $wpdb->insert_id. The only way to be 100% sure is to have add a key you know will be unique (and indexed as such); you can then retrieve the id by querying the table against that unique key.

The reason I write this is, if a trigger function adds rows from within the DB, or more importantly if a plugin hooks in wpdb in a such a way that it messes around with inserts alongside the one you're doing (e.g. for logging), you're not safe.

With that in mind, hardly anyone in the WP community (and most other communities, for that matter) has the slightest idea of what a DB can do, and treats the thing as if it's a bunch of huge arrays. So you're very safe to rely on it in practice.

share|improve this answer
Thanks a lot, very good answer! – Regis Zaleman Nov 30 '10 at 21:06
Just to add to the above answer, he's a WP bug related to this very issue: core.trac.wordpress.org/ticket/15465 – Denis de Bernardy Dec 1 '10 at 20:55

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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