phpcodeigniteroopmodelclassname

Calling CodeIgniter model method emits "Call to member function on non-object" error


I keep getting error:

Message: Call to a member function getbank() on a non-object

My controller code:

class Profile extends CI_Controller
{
    public function index()
    {
        $data = array();

        if ($query = $this->profile_model->getbank()) {
            $data['records'] = $query;
        }

        $this->load->view('profile_view', $data);
    }
}

What do I need to change and why?


Solution

  • Try this

    Controller

    class Profile extends CI_Controller
    {
        function index()
        {
            $data = array();
            $this->load->model('profile_model'); # Added
            $query = $this->profile_model->getbank(); # Changed
    
            if(!empty($query)) # Changed
            {
                $data['records'] = $query;
            }
    
            $this->load->view('profile_view', $data);
        }
    }
    

    Model

    class Profile_model extends CI_Model {
    
        public function getbank()  # Changed
        {
            $query = $this->db->get('bank');
            return $query->result();  # Changed
        }
    }
    

    Update

    Simple answer, thanks to all those who tried helping. I had the model file name with a small letter not a capital.

    Eg profile_model.php
    
    should be Profile_model.php
    

    However, this solution is elegant and simple, so it improved my code so il accept this one.