Error query php/codeigniter

Asked

Viewed 559 times

-2

I am using the code below to make a query in the database, but it is giving the following error:

PHP Error was encountered Severity: Notice Message: Undefined Property: Admin::$db Filename: core/Model.php Line Number: 51

Fatal error: Call to a Member Function query() on a non-object in /home/*/public_html/application/models/admin_model.php on line 4**

Code

class Admin_model extends CI_Model {
   public function carregar_hoteis(){
        $hoteis = $this->db->query("SELECT * FROM tabela");
        $array=array();
        foreach($hoteis->result() as $row)
        {
             $array['hoteis'][]=$row;
        }
        echo json_encode($array);
   }
}
  • By any chance, are you loading the library database? Just for free...

  • Shouldn’t be $this->db->get instead of $this->db->query?

  • @Ricardo o Codeigniter permite as duas formas. Give a look here: http://ellislab.com/codeigniter/user-guide/database/queries.html

2 answers

4


The problem is in the variable $this->db, which is not an object. Probably this variable receives an instance of the connection to the database, the connection should not be happening and therefore the value of the variable is null (and not an object).

Tip: check if the framework is connecting to the database and if, at the time of this code, an attempt was made to make a connection :)

  • 2

    is in my controller I had not given the last parameter to access the database as true.. for example: 
$this->load->model('Admin_model', 'model_admin',true);

  • 1

    @Silvioandorinha boa! do not forget to give a OK in the answer then, if you judge it correct :)

2

You initialized the Database library in the application/config/autoload.php file?

$autoload['libraries'] = array('database');

Browser other questions tagged

You are not signed in. Login or sign up in order to post.