0

I have been trying to return a $wpdb->insert_id; but unfortunately, it is returning null; What am I doing wrong here? I am sending data using ajax from the front end. Here is the backend code.

function add_fav() {

    global $wpdb;
    $table = $wpdb->prefix . "fav_products";
    $productID = (int) $_POST['product_id'];
    $response = []; 
    $insertid = 3;
    if(isset($_POST['amount'])) {
        $amount = (int) $_POST['amount'];
    }
    else{
        $amount = 1;
    }
    
    if(isset($_COOKIE['fav_id']) && !empty($_COOKIE['fav_id']))
    {
        $fav_id = $_COOKIE['fav_id'];
    }
    else
    {
        
        $fav_id = uniqid();
        setcookie('fav_id', $fav_id, strtotime('+1 year'), '/');
    }
      
    $itemInfav = $wpdb->get_row($wpdb->prepare("SELECT id, fav_id, product_id FROM $table WHERE fav_id = %s AND product_id = %d", $fav_id, $productID));
        
    if(!empty($itemInfav->product_id))
    {
        
        $response['sorry'] = "Sorry the product already exist in Wishlist!";
    
    }
    else
    {
        // insert 
        $toevoegen = $wpdb->insert( 
            $table, 
            array( 
                'fav_id' => $fav_id, 
                'product_id' => $productID,
                'amount' => $amount,
            ), 
            array( 
                '%s', 
                '%d',
                '%d' 
            ) 
        );
        $lastinsertid = $toevoegen->insert_id;
    }
    
    $totalInfav = $wpdb->get_row($wpdb->prepare("SELECT SUM(AMOUNT) as total FROM $table WHERE fav_id = %s", $fav_id));
    $response['result'] = $toevoegen;
    $response['fav_id'] = $fav_id;
    $response['total'] = $totalInfav->total;
    $response['insertid'] = $lastinsertid;
    wp_send_json( $response );
    wp_die();
}

And below is my database structure. I do have a foreign key in it.

CREATE TABLE $favtable (
   id int(11) NOT NULL AUTO_INCREMENT,
   product_id int(11) NOT NULL,
   fav_id varchar(255) NOT NULL,
   amount int(11) NOT NULL,
   created_at timestamp NOT NULL DEFAULT current_timestamp(),
   PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

And this is how the ajax on the front-end looks like.

$('body').on('click', '.addToFav', function(e)
    {
        e.preventDefault();
        
        var product_id = $(this).data('product-id'),
        ajax = $(this).data('ajax'),
        siteurl = $(this).data('url'),
        uid = $(this).data('uid'),
        $image = $('.'+uid).children('img'),
        img = document.createElement("img");
        img.src = siteurl+'/wp-content/themes/bg/assets/images/favorite-icon-white.svg',
        
        $.post(ajax, { 
            action: 'add_fav', 
            product_id: product_id}, 
            function(data){
                console.log(data);
                updateFavIcon(parseInt(data.total));    

                if( data.result ) { 
                    console.log(data.insertid); 
                    $('.'+uid).removeClass('addToFav');
                    $('.'+uid).addClass('addedFav');
                    $image.remove();
                    $('.'+uid).append(img);
                    $('.'+uid).data('wid', data.insertid);
                    $('.'+uid).attr('data-wid', data.insertid);
                    
                }
            });
    });

Can anybody please help me find out what am I doing wrong that the last insert id is not returning? Thanks in advance.

1 Answer 1

0

I have been trying to return a $wpdb->insert_id; but unfortunately, it is returning null;

That's not true, you haven't been returning $wpdb->insert_id at all.

        // insert 
        $toevoegen = $wpdb->insert( 
            ...
        );
        $lastinsertid = $toevoegen->insert_id;

You've been returning $toevoegen->insert_id, which is wrong. According to the docs $wpdb->insert will return either false or it will return the number of rows inserted:

This method returns false if the row could not be inserted. Otherwise, it returns the number of affected rows (which will always be 1).

false->insert_id is not valid and null. Neither is 1->insert_id.

Instead, return $wpdb->insert_id instead.

https://developer.wordpress.org/reference/classes/wpdb/#insert-row

2
  • It is inserting the data to the database and on check if($toevoegen){} It returns 1 But it is not returning the insert_id. Nov 3, 2021 at 1:09
  • Thanks, it solves the issues. Nov 3, 2021 at 1:14

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.