Miomir Dancevic
Miomir Dancevic

Reputation: 6852

How to check if id exist in CodeIgniter Cart?

Is there way to check if ID exist in CI Chart, and just upadte quantity, of that product, if not add new item?

This is what i have so far, but nothing is working :(

if (isset($_POST['sendorder']))
{
$qty=$_POST['productquantity'];

$data = array(
           'id'      => $id,
               'qty'     => $qty,
               'price'   => $price,
               'name'    => $heading
            );


if (count($this->cart->contents())>0){
                    foreach ($this->cart->contents() as $item){
                        if ($item['id']==$id){
                            $data = array('rowid'=>$item['rowid'],
                            'qty'=>++$item['qty']);
                            $this->cart->update($data);

                        }
            else{
                          $this->cart->insert($data);
                            }
                    }   

}
}

Upvotes: 0

Views: 4430

Answers (1)

Dhanang Pratama
Dhanang Pratama

Reputation: 27

Try this one

    // set $flag default value to true for inserting item to the cart session
    $insert_new = TRUE;
    $bag = $this->cart->contents();

    foreach ($bag as $item) {

        // check product id in session, if exist update the quantity
        if ( $item['id'] == '1' ) { // Set value to your variable

            $data = array('rowid'=>$item['rowid'],'qty'=>++$item['qty']);
            $this->cart->update($data);

            // set $insert_new value to False
            $insert_new = FALSE;

        }

    }

    // if $insert_new value is true, insert the item as new item in the cart
    if ($insert_new) {
        $data = array(
                'id' => 1,
                'qty' => 1,
                'price' => 40,
                'name' => 'Product item'
            );
        $this->cart->insert($data);

    }

Upvotes: 1

Related Questions