Search code examples
phpcodeignitermodels

How to properly call models in codeigniter?


I'm getting this Notice when loading a model.

 A PHP Error was encountered

        Severity: Notice

        Message: Undefined property: Users::$select

        Filename: controllers/users.php

        Line Number: 11

This is my Controller (users.php)

 <?php  
 class Users extends CI_Controller{  

 public function index(){  
     //load the database  
     $this->load->database();  
     //load the model  
     $this->load->model('users_model');  
     //load the method of model  
     $data['h']=$this->select->select();  
     //return the data in view  
     $this->load->view('users_view', $data);  
  }  
 }  
 ?> 

This is my Model (users_model.php)

<?php  
 class Users_model extends CI_Model  
 {  
  function __construct()  
  {  
     // Call the Model constructor  
     parent::__construct();  
  }  
  //we will use the select function  
  public function select()  
  {  
     //data is retrive from this query  
     $query = $this->db->get('users');  
     return $query;  
  }  
 }  
 ?>  

This is my View (users_view.php)

<table border="1">  
  <tbody>  
     <tr>  
        <td>Id</td>  
        <td>First Name</td>  
        <td>Last Name</td>  
        <td>E-mail ID</td>  
        <td>Password</td>  
        <td>Gender</td>  
        <td>Phone</td>  
        <td>Address</td>  
        <td>Is Admin</td>  
     </tr>  
     <?php  
     foreach ($h->result() as $row)  
     {  
        ?><tr>  
        <td><?php echo $row->id;?></td>  
        <td><?php echo $row->fname;?></td>  
        <td><?php echo $row->lname;?></td>  
        <td><?php echo $row->email;?></td>  
        <td><?php echo $row->password;?></td>  
        <td><?php echo $row->gender;?></td>  
        <td><?php echo $row->phone;?></td>  
        <td><?php echo $row->address;?></td>  
        <td><?php echo $row->admin;?></td>  
        </tr>  
     <?php }  
     ?>  
  </tbody>  

I'm new to CodeIgniter, need some help to know where I'm going wrong with my code.


Solution

  • Your call to the method of the model is wrong. You should call your model with the method you want to use in your controller, like this:

    $this->load->model('users_model');  
    $data['h']=$this->users_model->select();  
    

    Edit: when you load a model, you can send a second parameter as a rename of the model. Example:

    $this->load->model('users_model', 'select');  
    $data['h']=$this->select->select();  
    

    You should check the docs for more information about loading models