Call to a member function get() on a non-object

2019-02-16 02:14发布

问题:

I'm using the Codeigniter Framework and I'm getting the following error,

call to a member function get() on a non-object in site_model.php on line 11

which is the row with the get() . test is the name of my table in my database. What am i doing wrong?

<?php
    class Site extends CI_Controller 
    {
        function index()
        {
            $this->load->model('site_model');
            $data['records']= $this->site_model->getAll();
            $this->load->view('home',$data);
        }
    }

?>

<?php

    class Site_model extends CI_Model 
    {

        function getAll()
        {
            $q = $this->db->get('test');
            if($q->num_rows > 0 )
            {
                foreach ($q ->result() as $row )
                {
                    $data[] = $row ;
                }
            }
        return $data;
        }
    }

回答1:

My best guess is you didn't setup your database:

When a model is loaded it does NOT connect automatically to your database.

See the guide here: https://www.codeigniter.com/user_guide/general/models.html#connecting-to-your-database