WordPress get last insert id from database

260 views Asked by At

I want to get the last inserted id from the database I have tried many code am not able to get last insert id. I have given below the following my code. Please any one help and save me.

            $users_table = $wpdb->prefix."users";
            $saveFieldArray=array('user_login'=>'$utilisateurCand',
                                'user_pass'=>'$passeCand',
                                'user_email'=>'$emailCand', 
                                user_registered=>CURRENT_TIMESTAMP());
        $wpdb->insert( $users_table, $saveFieldArray);
        echo $wpdb->last_query;         
        echo $lastInsertId = $wpdb->insert_id; 
3

There are 3 answers

0
Stender On

Basically - if you use WPs own function, then you get the ID on success

Like this.

$userdata = array(
    'user_login' =>  $utilisateurCand,
    'user_pass'  =>  $passeCand,
    'user_email' =>  $emailCand,
);

$user_id = wp_insert_user( $userdata ) ;

// On success.
if ( ! is_wp_error( $user_id ) ) {
    echo "User created : ". $user_id;
}
0
rajat.gite On
$user_id = wp_insert_user(
array(
    'user_email'  =>  $emailCand,
    'user_pass' => $passeCand,
    'user_login' => $utilisateurCand,
    'role' => 'customer'
    )
);
if ( ! is_wp_error($user_id) ){
    wp_set_current_user( $user_id, $emailCand );
    wp_set_auth_cookie( $user_id, true, false );
    wp_redirect( home_url() );
}

Tested & works.

0
Niket Joshi On

I have tried the below code in my project to get the last inserted ID in wordpress, I paste my code below, Hope it helps you.

// While use wp_insert_post() use the below code
$post_ID = wp_insert_post($post);
print_r($post_ID);

Returns the ID of the post if the post is successfully added to the database. On failure, it returns 0 if $wp_error is set to false, or a WP_Error object if $wp_error is set to true.

When you used $wpdb->insert() function to store data in table, you can use below code.

$wpdb->insert()
$lastid = $wpdb->insert_id;

I hope this will helps you.