plugin development – $wpbd->insert_id is returning null

Question

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'), "https://wordpress.stackexchange.com/");
    }
      
    $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.

0
Jewel Mahmud 4 weeks 2021-11-02T17:47:04-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse