Codeigniter Load Model


Codeigniter load model : $this->load->model(ā€˜Your_model_nameā€™); is used to load models in Codeigniter.


Codeigniter Load Model Syntax

$this->load->model('Your_model_name');

Note if you are using subfolders in models. Example your model file is within the ā€œapplication/models/usersā€
folder then in this case you need to load the models in this way :

$this->load->model('your_sub_foler_name/your_model_name');

For Example : load model users_model which is inside the users folder.

$this->load->model('users/users_model');
Codeigniter Load Model Example

Codeigniter Load Model Example

If you want to load model in library Read ā€“ http://tutorialsplane.com/codeigniter-load-model-in-library/

Codeigniter Load Model Example

1. Create Model :
place it in application/models folder

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class My_first_model extends CI_Model {
 function __construct()
    {
        parent::__construct();
    }
   public function getData(){

     $query = this->db->get('users',10);
     return $query->result_array();

  }

}
?>

2. Create Controller :
place it in application/controllers folder

Now Load model from and get data from users table.

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class MyUsers extends CI_Controller {
 
   public function users(){
     //load model
     $this->load->model('My_first_model');
     // now call model method 
     $data['users'] = $this->My_first_model->getData();
     $this->load->view('MyUsers_view', $data);

  }

}
?>

3. Create view :
place it in application/views folder

Now We are going to print user data from users table.

<html>
<title>Model Demo</title>
<head>
<style>
.mytable{
border:1px solid gray;
padding:5px;
}
</style>
</head>
<body>
<table class="mytable">
  <tr><td>Id</td><td>Name</td><td>Email</td><td>Phone</td></tr>
  <?php 
 if(count($users)>0){
  foreach($users as $user){
  ?>
<tr><td><?php echo $user['id'];?></td><td><?php echo $user['name'];?></td><td><?php echo $user['email'];?></td><td><?php echo $user['phone'];?></td></tr>
 <?php
  }
}else{
?>
<tr><td colspan="4">No User Found.</td></tr>
<?php 
}
?>
</body>
</html>

Now Access the url ā€œhttp://localhost/MyUsers/usersā€

DemoĀ»


Advertisements

User Ans/Comments

Why does no one list out the model file name? Is it supposed to have _model, or _Model, or nothing as a suffix? Or all lower case?
Ā George Butiri
Hi George Butiri,You can take any name such as - My_Model, MyModel or mymodel. It depends up to you..
Ā Anil Yadav

Add Comment

šŸ“– Read More