Blog Details



* What is a Model ?:-

  • Models are optionally available for those who want to use a more traditional MVC approach.
  • Models are PHP classes that are designed to work with information in your database.

Structure of a Model :-

class Model_name extends CI_Model { function __construct() { parent::__construct(); } }


  • Class names must start with an uppercase letter. In other words, this is valid:

Loading a Model:

  • Your models will typically be loaded and called from within your Controller functions. To load a model you will use the following function:
  • $this->load->model('Model_name');
  • $this->Model_name->function();
  • If you would like your model assigned to a different object name you can specify it via the second parameter of the loading function:
  • $this->load->model('Model_name', 'fubar');
  • $this->fubar->function();


Step 1 :

  • Let's create a simple Model so you can see it in action. Using your text editor, create a file called blogmodel .php , and put the following code in it:
class Blogmodel extends CI_Model { var $title   = ''; var $content = ''; var $date    = ''; function __construct() { // Call the Model constructor parent::__construct(); } function get_last_ten_entries() { $query = $this->db->get('entries', 10); return $query->result(); } function insert_entry() { $this->title   = $_POST['title']; // please read the below note $this->content = $_POST['content']; $this->date    = time(); $this->db->insert('entries', $this); } function update_entry() { $this->title   = $_POST['title']; $this->content = $_POST['content']; $this->date    = time(); $this->db->update('entries', $this, array('id' => $_POST['id'])); } }
  • Then save the file blogmodel.php  to your application/models/ folder.

Step 2 :

  • Let's create a simple controller so you can see it in action. Using your text editor, create a file called blog_controller.php , and put the following code in it:
class Blog_controller extends CI_Controller { function blog() { $this->load->model('blogmodel'); $data['query'] = $this->blogmodel->get_last_ten_entries(); $this->load->view('blog', $data); } }
  • Then save the file blog_controller.php to your application/controller/ folder.



Latest posts

Implementing CRUD Operations ¶

<ul> <li>Now comes the fun part. We would like t


<ol> <li><a href="

Creating Model

<ol> <li><a href="

Get Free Quote