Shopping basket

When I create a shopping cart with the CI Cart Class, it first adds the product to the cart, and then when I add this product to the cart, the next time it also adds 1 product, not 2.

I want to do this, the quantity in the cart increases when someone adds the product to their cart, and the same item is already in the cart.

+1
source share
1 answer

It would be helpful if you could post some code or what data you send to the cart class, but this should point you in the right direction:

function add_cart_item(){ $data = $_POST; $id = $data['product_id']; //get new product id $qty = $data['quantity']; //get quantity if that item $cart = $this->cart->contents(); //get all items in the cart $exists = false; //lets say that the new item we're adding is not in the cart $rowid = ''; foreach($cart as $item){ if($item['id'] == $id) //if the item we're adding is in cart add up those two quantities { $exists = true; $rowid = $item['rowid']; $qty = $item['qty'] + $qty; } } if($exists) { $this->cart_model->update_item($rowid, $qty); echo 'true'; // For ajax calls if javascript is enabled, return true, so the cart gets updated } else { if($this->cart_model->add_cart_item() == TRUE) { echo 'true'; // for ajax calls if javascript is enabled, return true, so the cart gets updated } } } 

and in cart_model you will have an update and add functions that look something like this.

 function update_item($rowid, $qty){ // Create an array with the products rowid and quantities. $data = array( 'rowid' => $rowid, 'qty' => $qty ); // Update the cart with the new information $this->cart->update($data); } // Add an item to the cart function add_cart_item(){ $id = $this->input->post('product_id'); // Assign posted product_id to $id $qty = $this->input->post('quantity'); // Assign posted quantity to $cty //$img = $this->input->post('image'); // Assign posted quantity to $img $this->db->where('id', $id); // Select where id matches the posted id $query = $this->db->get('products', 1); // Select the products where a match is found and limit the query by 1 // Check if a row has been found if($query->num_rows > 0){ foreach ($query->result() as $row) { $data = array( 'id' => $id, 'qty' => $qty, 'price' => $row->price, 'name' => $row->name, //'options' => array('image' => $img), ); $this->cart->insert($data); return TRUE; } // Nothing found! Return FALSE! }else{ return FALSE; } } 
+4
source

All Articles