How to Create and Load Model in CodeIgniter

In CodeIgniter Model are the PHP classes where all database related manipulation is done e.g. fetching records, insert, update, and delete records.

Within this, all data processing logic is done.

All model files are managed in application/models directory and they are load and access by the controller.

How to Create and Load Model in CodeIgniter


Contents

  1. Load Database
  2. Create Model
  3. Controller
  4. Conclusion

1. Load Database

First, need to load the database library for performing any database related manipulation.

Navigate to application/config/database.php and define Database connection.

$db['default'] = array(
 'dsn' => '',
 'hostname' => 'localhost',
 'username' => 'root', // Username
 'password' => '', // Password
 'database' => 'tutorial', // Database name
 'dbdriver' => 'mysqli',
 'dbprefix' => '',
 'pconnect' => FALSE,
 'db_debug' => (ENVIRONMENT !== 'production'),
 'cache_on' => FALSE,
 'cachedir' => '',
 'char_set' => 'utf8',
 'dbcollat' => 'utf8_general_ci',
 'swap_pre' => '',
 'encrypt' => FALSE,
 'compress' => FALSE,
 'stricton' => FALSE,
 'failover' => array(),
 'save_queries' => TRUE
);

Load Database

Open application/config/autoload.php and add the database in libraries array().

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

Default controller

Open application/config/routes.php and edit default_controller value to User.

$route['default_controller'] = 'User';

2. Create Model

Create a Main_model.php file in application/models directory.

Within the class create methods for data processing.

I have created a getUsers() method to select all records from the users table and return an Array response.

Completed Code

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

class Main_model extends CI_Model {

  function getUsers(){
 
    $response = array();
 
    // Select record
    $this->db->select('*');
    $q = $this->db->get('users');
    $response = $q->result_array();

    return $response;
  }

}

3. Controller

Model is load from the controller.

Here, is the syntax for loading Model and accessing methods.

Syntax (loading model) –

$this->load->model(Model-class-name);

Syntax (call model method) –

$this->[Model-class-name]->method-name();

Create a User.php file in application/controllers directory.

Load above created Main_model using $this->load->model('Main_model') method in the __construct() method and call getUsers() method using $this->Main_model->getUsers().

Store the return response in a $data variable.

Completed Code

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

class User extends CI_Controller {

  public function __construct(){

     parent::__construct();

     // Load model
     $this->load->model('Main_model');
  }

  public function users(){

    // get data from model
    $data = $this->Main_model->getUsers();

  }

}

4. Conclusion

Manage all model files in application/models directory and in the controller it is better to load the models from the __construct() method if you want to use them in more than one method.

If you found this tutorial helpful then don't forget to share.

2 thoughts on “How to Create and Load Model in CodeIgniter”

  1. Hello,
    I upgraded php version from 5.6 to 7
    but after that i found error like this

    Type: Error
    Message: Using $this when not in object context
    Filename: /home/ausecoma/public_html/application/models/Temp_model.php
    Line Number: 154

    and this is my function
    function get_page_by_username($username)
    {
    $this->db->select(‘pages.*, categories.name as category_name, places.name as place_name, places.place1, places.place1_id, places.place2, places.place2_id, places.place3, places.place3_id’);
    $this->db->from(‘pages’);
    $this->db->join(‘categories’, ‘pages.category_id = categories.id’, ‘left’);
    $this->db->join(‘places’, ‘pages.place_id = places.id’, ‘left’);
    $record = $this->db->where(array(‘pages.username’ => $username))->get()->row();
    if( !empty($record) ) {
    return $record;
    } else {
    return FALSE;
    }
    }

    can you pleas suggest on this.

    Reply

Leave a Comment