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.

0


source to share


3 answers


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

      

+5


source


In CodeIgniter, you must load the database model before using it. Use $this->load->database();

to load the database model.



+3


source


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.

+2


source







All Articles