问题
When i create a shopping cart with CI Cart Class, it add the product to the cart first 1 and then when i add that product to the cart next time it is also add 1 product not 2.
I want to do it the quantity in the cart is increased when someone adds an item to their cart and that exact same item is already in the cart.
回答1:
It would be helpful if you could post some code or what data you are sending 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 the cart_model you would have update and add functions that look something like this
function update_item($rowid, $qty){
// Create an array with the products rowid's 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;
}
}
来源:https://stackoverflow.com/questions/12216039/codeigniter-shopping-cart