Codeigniter model error
I created a new model class both my_model.php
inside a folder /models
and a function inside it to load all elements:
function get_all(){
$query = $this->db->get('test'); //test is my table
return $query->result();
}
In the controller, I instantiated the class and called the method;
$this->load->model('my_model');
$res = $this->my_model->get_all();
But this throws me a message:
Fatal error: Calling member function get () for non-object in / var / www / testapp / application / models / my _model.php on line 7
This line 7 points to the piece of code that I used $this->db
. I tried to see the value $db
, but I think it is a magic accessor __get
and __set
therefore I was not able to see the value of this property before calling this method.
I tried searching on several other cases, but none of them matched my scenarios and most likely none of them were able to solve my problem.
source to share
First you need to load the database
$this->load->database();
So the whole code:
function get_all(){
$this->load->database();
$query = $this->db->get('test'); //test is my table
return $query->result();
}
Or , load the database into your __construct
method.
Or , IMO, Better to autoload the database by changing the application/config/autoload.php
example below.
$autoload['libraries'] = array('database','form_validation'); //form_validation is for example only
source to share
Your error is actually pretty simple:
return $query->result;
Should be:
return $query->result();
Sometimes the line number reported by the PHP error is not exactly what you think the parser just does best and tells you where it encountered the error.
There is one more problem:
$res = $this->my_model->getAll();
Should be:
$res = $this->my_model->get_all();
You have named your own function with the wrong name.
source to share