WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] How to get primary key of last inserted row into database? (8 posts)

  1. mocheng
    Member
    Posted 4 years ago #

    My plugin has a table with a 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.

    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 last operation. My operation with 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?

  2. MichaelH
    Member
    Posted 4 years ago #

    Something like:

    $lastid = $wpdb->get_col("SELECT ID FROM wp_posts ORDER BY ID DESC LIMIT 0 , 1" );

    Remember you can always use phpMyAdmin to help develop a SQL query.

  3. cayrol272
    Member
    Posted 4 years ago #

    i also have a similar problem as above but i using mysqli_fetch_assoc give an error when i using $wpdb.

  4. mocheng
    Member
    Posted 4 years ago #

    Hi Michael,

    If some more rows are inserted by other session before the $wpdb->get_col(...) is executed, would it be return invalid value?

    What I want is to using AJAX to post data to 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 server at the same time. So, I have to make sure that each AJAX request get the EXACT new row ID in response.

  5. MichaelH
    Member
    Posted 4 years ago #

    Not sure of the answer except to point to the MySQL function LAST_INSERT_ID().

  6. mocheng
    Member
    Posted 4 years ago #

    I found the correct way.
    http://codex.wordpress.org/Function_Reference/wpdb_Class#Class%5FVariables

    I checked wordpress sourcecode. The class varialbe $wpdb->insert_id is updated with mysql_insert_id with connection identifier.

  7. MichaelH
    Member
    Posted 4 years ago #

  8. mocheng
    Member
    Posted 4 years ago #

    correct:) stackoverflow is another good source as codex does.

Topic Closed

This topic has been closed to new replies.

About this Topic