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?


1 Answer 1


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.


Your Answer

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

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