I am trying to implement cart functionality in codeigniter. In my controller I have a public function add
and in my model a public function called get
to fetch data from database according to the product selected.
here is my Controller
public function add() {
$id = $this->input->post('id');
$product = $this->products_model->get($id);
echo "<pre>";
print_r($product); die();
$data = array(
'id' => $id,
'name' => $product->pro_name,
'qty' => 1,
'price' => $product->pro_price
);
$this->cart->insert($data);
}
and here is my Model
public function get($id) {
$results = $this->db->get_where('products', array('pro_id' => $id));
return $results->result_array();
}
When I print_r($product)
I get an array like this.
Array
(
[0] => Array
(
[pro_id] => 1
[pro_name] => Beef Carrot & Pea Food
[pro_price] => 150.00
[pro_image] => 1.png
)
)
But when I try to insert in the data array I get this error.
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: controllers/cart.php
Line Number: 11
Backtrace:
File: E:\xampp\htdocs\ci\dogschew\application\controllers\cart.php
Line: 11
Function: _error_handler
File: E:\xampp\htdocs\ci\dogschew\index.php
Line: 315
Function: require_once
Hope this will help you :
Since u r using single item with object in your controller,So you should use row()
instead of result_array()
;
Your model should be like this :
public function get($id)
{
$results = $this->db->get_where('products', array('pro_id' => $id));
return $results->row();
}
Your controller should be like this :
Print $data
in your controller to check it has data;
public function add()
{
$id = $this->input->post('id');
$product = $this->products_model->get($id);
$data = array(
'id' => $id,
'name' => $product->pro_name,
'qty' => 1,
'price' => $product->pro_price
);
print_r($data); die();
$this->cart->insert($data);
}
For more : https://www.codeigniter.com/user_guide/database/results.html