7

I'm using $wpdb->insert to insert data to my plugin table. How can I get the id of the new line I Just insert. Because I have a lot of users that add data to the table I can't use $wpdb->insert_id Because it's not necessary the last one.

2 Answers 2

15

There is no other way, but I can not see how you need any other way then this. I believe that the insert ID accessed by $wpdb is the last ID by this instance of WPDB, other inserts should not affect that but I'm not sure.

<?php

  $wpdb->insert("QUERY");

  $this_insert = $wpdb->insert_id;

?>
3
  • 2
    $wpdb is global, all queries share the same instance.
    – fuxia
    Commented Nov 2, 2016 at 10:44
  • 1
    @toscho but does a query by another user influences the insert ID you get back if they insert a query just in between your insert and read out? Commented Nov 3, 2016 at 13:55
  • 3
    No it doesn't. $wpdb is global, but only in this one request, it's not shared between requests of multiple users. As it's also not asynchronous, this will work as expected.
    – janh
    Commented Oct 8, 2017 at 7:31
1

$wpdb->insert_id is global withint the database session. since Wordpress creates a new session per user session this is not a problem, even when using a connection pooling. the only caveat is that this variable will always have the last inserted auto-increment ID, so you have to check after each insert. If you really want to capture the list of new inserted records, you can do it inside a stored procedure and capture it in a transaction. or inside a trigger.

1
  • Of course, the important step is to save it right below after the insert() before other inserts will eventually occurs by other code or plugins etc.
    – DrLightman
    Commented May 9 at 13: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.