I want to update the quantity of a shopping cart when the item is already in the cart
and add it when it is not(added in the cart)
. I'm confused on how to solve the twist of this problem. I've google a lot of the same problem but there is no same exact problem/solution for this.
Here is the code of my view:
<?php if($lab): ?>
<table class="table table-striped">
<tr>
<th>Description</th>
<th>Price</th>
<th>Action</th>
</tr>
<?php foreach($lab as $rows): ?>
<tr>
<td><?php echo $rows->ldesc; ?></td>
<td><?php echo $rows->lprice; ?></td>
<td><button value="<?php echo $rows->lid; ?>" class="btn btn-info addlabtype"><i class="icon-plus"></i></button></td>
</tr>
<?php endforeach; ?>
</table>
<?php endif; ?>
<script type="text/javascript" >
(function(){
$(document).on('click','.addlabtype',function(){
var id= $(this).val(),
dataString = "id=" + id;
$.ajax({
type:"POST",
url: base_url + "inpatient/addlab",
data:dataString,
success:function(data){
$('.pickedlab').html(data);
}
})
});
})()
</script>
Here is my controller:
public function addlab(){
$data['cart'] = $this->inpatient_model->addlab();
$this->load->view('admin/addeddiag',$data);
}
And here is my model:
public function addlab(){
$this->db->select('*');
$this->db->from('lab');
$this->db->where('lid',$this->input->post('id'));
$q = $this->db->get();
$lab = $q->result_array();
$cart = $this->cart->contents();
if($cart){
foreach($cart as $items){
if($this->input->post('id') == $items['id'] ){
$this->cart->update(array(
'rowid' => $items['rowid'],
'qty' => $items['qty'] + 1
));
}else{
$data = array(
'id' => $lab[0]['lid'],
'name' => $lab[0]['ldesc'],
'qty' => 1,
'price' => $lab[0]['lprice']
);
$this->cart->insert($data);
}
}
}else{
$data = array(
'id' => $lab[0]['lid'],
'name' => $lab[0]['ldesc'],
'qty' => 1,
'price' => $lab[0]['lprice']
);
$this->cart->insert($data);
}
return $this->cart->contents();
}
And yes one thing that is wrong in my code is the foreach in my model. I really have no idea on how to fix it. Because when I try to click .addlabtype
for example I have 3 items in my cart and when I try to update it, it will not update unless it is the last item that I added in my cart.
Sorry for my English. Thanks in advance!
Edit:
To sum it up, how can I get the rowid
of a specific id
in the cart?