How to get last inserted row ID from WordPress database?

前端 未结 5 744
迷失自我
迷失自我 2020-12-04 10:58

My WordPress 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

相关标签:
5条回答
  • 2020-12-04 11:24

    This is how I did it, in my code

     ...
     global $wpdb;
     $query =  "INSERT INTO... VALUES(...)" ;
     $wpdb->query(
            $wpdb->prepare($query)
    );
    return $wpdb->insert_id;
    ...
    

    More Class Variables

    0 讨论(0)
  • 2020-12-04 11:26

    Straight after the $wpdb->insert() that does the insert, do this:

    $lastid = $wpdb->insert_id;
    

    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 讨论(0)
  • 2020-12-04 11:35

    I needed to get the last id way after inserting it, so

    $lastid = $wpdb->insert_id;
    

    Was not an option.

    Did the follow:

    global $wpdb;
    $id = $wpdb->get_var( 'SELECT id FROM ' . $wpdb->prefix . 'table' . ' ORDER BY id DESC LIMIT 1');
    
    0 讨论(0)
  • 2020-12-04 11:37

    Something like this should do it too :

    $last = $wpdb->get_row("SHOW TABLE STATUS LIKE 'table_name'");
    $lastid = $last->Auto_increment;
    
    0 讨论(0)
  • 2020-12-04 11:46

    Putting the call to mysql_insert_id() inside a transaction, should do it:

    mysql_query('BEGIN');
    // Whatever code that does the insert here.
    $id = mysql_insert_id();
    mysql_query('COMMIT');
    // Stuff with $id.
    
    0 讨论(0)
提交回复
热议问题