I want to fetch some data from mysql. I am using codeigniter model and controller for this.
CI_model.php :
public function getLastSale($id){
$q = $this->db->query("SELECT * from sma_sales desc limit 1 where customer_id = '$id' ");
$result = $q->row();
$res = array();
$res['id'] = $result->id;
$res['paid'] = $result->paid;
return $res;
}
CI_controller.php :
$getLastData = $this->pos_model->getLastSale($customer_id);
$sid = $getLastData['id'];
$prepaid = $getLastData['paid'];
But this error is showing :
An uncaught Exception was encountered
Type: Error
Message: Call to a member function row() on boolean
I am a beginner of codeigniter. What am i doing wrong ?
I think the problem is with the query:
SELECT * from sma_sales desc limit 1 where customer_id = '$id'
Try something like this:
SELECT * from sma_sales where customer_id = '$id' order by `sales_date` desc limit 1
You need to use the ORDER BY
clause to do the sorting.
Also, make sure you escape the $id
before including it inside the query. Have a look at this.
Another suggestion is that, you could check whether the $result
is set or not. Because in case of errors, it would return NULL. Read more about it here.