Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

Thanks!

share|improve this question
add comment

1 Answer

up vote 3 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 Dec 1 '10 at 20:55
add comment

Your Answer

 
discard

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.