Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k points)

My WordPress plugin has a table with an AUTO_INCREMENT primary key field called ID. When a new row is inserted into the table, I'd like to get the ID value of the insertion.

The feature is to use AJAX to post data to a server to insert into DB. The new row ID is returned in the AJAX response to update client status. It is possible that multiple clients are posting data to the server at the same time. So, I have to make sure that each AJAX request gets the EXACT new row ID in response.

In PHP, there is a method called mysql_insert_id for this feature. But, it is valid for race condition only if the argument is link_identifier of the last operation. My operation with the database is on $wpdb. How to extract the link_identifier from $wpdb to make sure mysql_insert_id work? Is there any other way to get the last-inserted-row id from $wpdb?

Thanks.

2 Answers

0 votes
by (106k points)
edited by

If you want to get the last inserted row ID from the WordPress database. You can use the $wpdb->insert() it does the insert.

Want to learn Angularjs from basics! Here's the right video for you on  Angularjs provided by Intellipaat:

$lastid = $wpdb->insert_id;

You can find more information about how to do things the WordPress way can be found in the WordPress codex. The details above were found here on the wpdb class page.

0 votes
ago by (1.8k points)

You can use the $wpdb->insert() method to get the last inserted row ID in WordPress. This is based on the fact that it actually carries out the insertion of data into the database.

 This way, after you have done the insert, you will be able to get the last inserted ID using $wpdb->insert_id. This holds the ID of the last row inserted automatically and, therefore, can be easily accessed without much ado on details concerning database connection handling like link_identifier. 

This method is very efficient and works reliably even for multiple clients making simultaneous AJAX requests; each gets the correct new row ID in the response.

Related questions

+1 vote
1 answer
0 votes
1 answer
0 votes
1 answer
asked Jul 13, 2019 in SQL by Tech4ever (20.3k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...