Ricky Kurniawan Ricky Kurniawan - 6 months ago 28
PHP Question

Codeigniter - Why adding to cart didn't work?

I have a problem, when I try to add cart to shopping cart. Cart cannot enter to shopping cart.

And this is my controller:

public function buy($product_id)
{
$product = $this->m_produk->find($product_id);
$data = array(
'id' => $product->id,
'qty' => 1,
'nama' => $product->nama,
'harga' => $product->harga
);

$this->cart->insert($data);
redirect('produk/index');
}


This is my model to add cart:

public function find($id){
$hasil = $this->db->where('id',$id)
->limit(1)
->get('produk');
if ($hasil->num_rows() > 0) {
return $hasil->row();
}else {
return array();
}
}


And this is my view:

<?php

foreach ($produk as $product) {

?>
<div class="thumbnail">
<img src="<?php echo base_url(''.$product->gambar);?>" width="200" height="200" class="img-rounded center-block" alt=""/>
<div class="caption">
<h4 class="text-center"><?php echo $product->nama?></h4>
<h4 class="text-center">RP.<?php echo $product->harga?>,00</h4>
<!-- <a href="#" class="link-class btn btn-primary center-block" role="button">add to cart</a> -->
<?=anchor('produk/buy/'.$product->id,'add to cart' , [
'class' => 'btn btn-primary' , 'role' => 'button'
]) ?>
</div>
</div>
<?php } ?>
</div>


PS: when I
print_r
my content, cart just displays:
array()
its means when I add cart, cart cannot enter to shopping cart.

Can anyone solve this?

Thanks.

Answer

as per documentation you have referred to: https://ellislab.com/codeigniter/user-guide/libraries/cart.html

Important: The first four array indexes above (id, qty, price, and name) are
required. If you omit any of them the data will not be saved to the cart. The
fifth index (options) is optional. It is intended to be used in cases where your
product has options associated with it. Use an array for options, as shown
above.

Please pass all the required parameters. you have got name misspelled or missing, price missing