By Stephen Thorpe

Untangling MVC with CodeIgniter

By Stephen Thorpe

When I first started programming the only type of code I wrote was procedural. You know the type, one thing leads to another with a thrown in function here and there and you have a working application. As I grew as a programmer, I began to find out that way of programming is fine for small projects but when I started to develop bigger applications my code became very disorganized and hard to read. To combat this I started writing my own classes to help me write better, reusable code that I could use in all my applications. Then I realized that although I was learning a lot by doing this, I was reinventing the wheel. Most of what I was writing had already been accomplished many times over in various PHP frameworks. I began looking into the almost endless selection of PHP frameworks and saw most of them were also based on something called MVC.

Learning to program using MVC was a complete paradigm shift for me, but it was well worth the struggle. If you want to develop applications with sell-structured, readable code that you can quickly diagnose problems in, then MVC is for you. In this article I’ll untangle the mysteries of MVC for you using CodeIgniter, a PHP framework based on the MVC pattern. I’ll first present a high level overview of MVC, what it is and how it can help you to become a better programmer, and then guide you through writing a simple web form the CodeIgniter way so you can see how the pattern looks in action.

What is MVC?

MVC is another acronym you’ll want to add to your endless book of acronyms; it stands for Model-View-Controller and is an software architectural design pattern. Adhering to the MVC pattern of will separate your application’s logic from its data and presentation. If you have ever seen code like this:

<?php if($somthing == $thisthing) echo "<p>Hello there</p>"; ?>

then you completely understand how a page full of mixed up PHP and HTML can become really hard to maintain and read. So let’s look at each part of MVC and see what each part represents.

  • Model – encapsulates your data management routines. Usually this is the part of your code that retrieves, inserts, updates, and deletes data in you database (or whatever else you’re using for a data store).
  • View – encapsulates the information that is presented to a user. This is the actual web page, RSS feed, or even a part of a page like a header of footer.
  • Controller – coordinates the Model and View parts of your application to respond to the request. A controller accepts input from the user and instructs the model and a view to perform actions based on that input; it controls the flow of information in the application.

To better understand how the MVC pattern works, let’s look at the steps you would take to code a PHP form using this pattern.

  1. The user interacts with the View which presents a web form.
  2. The user submits the form, and the Controller receives the POST request. It passes this data to the Model.
  3. The Model updates and queries the database and sends the result back to the Controller.
  4. The Controller passes the Model’s response to the View.
  5. The View updates itself with the new data and is displayed to the user.

Installing CodeIgniter

With so many MVC frameworks out there, how do you decide which one to choose – don’t they all provide similar functionality just differing slightly in their implementation and syntax? I had never used a framework before so I had to read through a lot of documentation and experiment with them to find out which one was right for me. I found that CodeIgniter had a much smaller learning curve then the others, which is probably why it has a reputation for being great for beginners. It’s documentation is very clear and provides many code examples to help you along the way. Although in this article I’ll be using CodeIgniter, the concept of MVC will be applicable to almost any framework you choose.

CodeIgniter is a cinch to install and configure for you system. Follow these steps and you’ll be up and running in less then five minutes.

  1. Download the latest version of CodeIgniter. As of this writing, the latest version is 2.0.3.
  2. Uncompress the archive and place the uncompressed directory in your web root.
  3. Rename the directory from CodeIgniter_2.0.3 to CI
  4. Open CI/application/config/config.php and change the base URL to your server. In my case, it is: $config['base_url'] = "http://localhost/CI";
  5. Go to the CI directory on the server using your web browser. Again, in my case it’s http://localhost/CI.

You’ve now finished the CodeIgniter installation and should see a web page like the one below:


Now that you have everything installed you’ll have probably noticed all the directories that CodeIgniter has. Don’t be intimidated; you won’t have to deal with most of them since the majority of your work will take place in the system/application directory.

Looking in the system/application directory there are subdirectories named controllers, models, and views. This is where you will place your files for your application. Your controller files will be in the controllers directory, model files in the models directory, and view files in the views directory.


Less Talk, More Code

Now that you have a basic understanding of what the MVC architecture is and have CodeIgniter installed, let’s get down to some coding. In this example you’ll create a very simple form to collect email addresses using CodeIgniter’s form helper classes and form validation library. Let’s get started.

Create the Controller

Create a new file in your application/controllers directory named sitepointform.php that contains the following code:

class Sitepointform extends CI_Controller
    public function index() {
        // Load the Form helper which provides methods to assist
        // working with forms.
        // Load the form validation classes

        // As you have loaded the validation classes, you can now
        // apply rules to the fields you want validated. The
        // functions below take three arguments:
        //     1. The name of form field
        //     2. The human name of the field to be displayed in
        //        the event of an error
        //     3. The names of the validation rules to apply
        $this->form_validation->set_rules("first", "First Name",
        $this->form_validation->set_rules("last", "Last Name",
        $this->form_validation->set_rules("email", "Email Address",

        // Check whether the form validates. If not, present the
        // form view otherwise present the success view.
        if ($this->form_validation->run() == false) {
        else {

Create the Views

Next, create a file in your application/views directory called sitepointform_view.php with this code:

// Display any form validation error messages
echo validation_errors();

// Using the form helper to help create the start of the form code
echo form_open("sitepointform");
   <label for="first">First Name</label>
   <input type="text" name="first"><br>

   <label for="last">Last Name</label>
   <input type="text" name="last"><br>

   <label for="email">Email Address</label>
   <input type="text" name="email"><br>

   <input type="submit" name="submit" value="Submit">

Create the file application/views/formsuccess_view.php with this code which will be showed later when a form is successfully submitted:

  <title>Form Success</title>
  <h3>Your form was successfully submitted!</h3>
  <p><a href="http://localhost/CI/index.php/sitepointform">Enter a new
email address!</a></p>

Now visit http://localhost/CI/index.php/sitepointform/index and you’ll see your newly created form:


The URL follows this pattern in your application:


Here sitepointform is the controller class, and index is the desired method. If you were renamed the method to myForm(), the URL would change like this:


In the absence of a method in the URL, CodeIgniter will assume index.

Hit submit without any input in the text fields to try out the validation. You’ll see CodeIgniter enforcing the rules you set up earlier in the controller and displays the error messages.

Create the Model

Now that you have your form built, you need somewhere to store all the names and email addresses. Create a table addresses with the following statement in your database:

CREATE TABLE addresses (
    last_name VARCHAR(128) NOT NULL,
    first_name VARCHAR(128) NOT NULL,
    email VARCHAR(128) NOT NULL,
    PRIMARY KEY (id)

With the database table in place, now you have to tell CodeIgniter where it is. Open up application/config/database.php and enter your database credentials. Specify appropriate values for the hostname, username, password, database, and dbdriver keys.

Then, create application/models/sitepointform_model.php with this code:

class Sitepointform_model extends CI_Model
    public function insert_address($data) {
        $this->db->insert("addresses", $data);

The class has a method named insert_address() that is accepts the array of values passed in from the controller. CodeIgniter has a database class built in so you don’t have to write any SQL at all; $this->db->insert() will automatically generate and execute the SQL for you.

Try it Out

To use the model from the controller, open up application/controllers/sitepointform.php and update the index() method as follows:

public function index() {

    $this->form_validation->set_rules("first", "First Name",
    $this->form_validation->set_rules("last", "Last Name",
    $this->form_validation->set_rules("email", "Email Address",

    if ($this->form_validation->run() == false) {
    else {
        $first = $_POST["first"];
        $last = $_POST["last"];
        $email = $_POST["email"];
        $data = array("first_name" => $first,
                      "last_name" => $last,
                      "email" => $email);


The incoming data posted from the form is placed into an associative array to be passed into the model’s insert_address() method. Note the keys in the array have the same names as the columns in the addresses table. This is important for the final step in creating the model. Then the model is loaded with $this->load->model(), the data is passed to the insert_address() method, and the success view is displayed.

Go back to http://localhost/CI/index.php/sitepointform and enter some data. If you fill in all the text fields correctly you’ll see the success page and the data is now in your database.



Hopefully you now understand what MVC is all about, a way of separating pieces of your code based on their function to keep everything more organized. Though CodeIgniter happens to be my framework of choice, knowledge of the pattern is applicable to almost any other framework you choose, and of course you can implement it in your own code without a framework as well.

Image via Alexey Rozhanovsky / Shutterstock

  • Selorm Nelson

    Thanks a lot for this, I’m working on a new project and torn between creating my own Tiny MVC or using an existing one and if the MVC code structure is really necessary. :)

    • Stephen Thorpe

      Thanks Selorm this was my first tech article so I’m glad it could help you with you new project. Don’t forget to “Like” or “tweet” the article around, you never know it could help others in the same boat as you. Thanks for visiting

  • Z

    Thanks a lot! Hopefully there are more CI tutorials to come and hopefully also it cover on building application like shopping cart, cms or so on.

    Good job!

    • Stephen Thorpe

      Z if those are the type of articles that people are asking for I know we will have more in the near future. Keep us posted on any other ideas you would like to see. Thanks.

  • Thanks for this great tutorial. I always wanted to know how to implement this architecture in PHP and here i found CodeIgniter.

  • Thanks for the article. I have just taken the plunge into MVC and am loving articles like these. I looked at CI, but in the end opted to build my own mini-framework and include components from other glue type libraries such as Zend. I’m sure that CI is great, but it seems to be very tightly wrapped, I seem to learn best by figuring out and writing the code myself. One area of division I have found in different articles about MVC is how much should be in the controller (thick or thin) and if the view should be able to communicate with the model directly. Thanks again!

    • Hey Alex – From what I read from other tutorials, business logic is best kept in Models, so thin controller, thick models would be good practise.

      Thanks for the article Stephen! I am also just diving into CodeIgniter, though I did Struts (a Java MVC) a loooooooong time ago!

      • Whilst this tutorial is not perfect it does correctly show how to use a model; that is to keep it lean so that it does not need to concern itself with where the data is coming from.

        Likewise the model does not need to concern itself with whether the data meets certain application-specific criteria – that is the job of the controller. A lean model is a flexible model.

        If you always pass your form data to the model in an array, then down the track you can pass in data from another source (ie. an API) without having to redesign the model.

        • NotImportant

          Not according to pattern pundits/practitioners :o fat model – thin controller is definitely the accepted best practice – that includes validation and most logic.

    • The controller is your interface to the outside world. Its not designed to handle transforms or business logic. Its how your HTTP requests come in or SOAP, etc. So you use it like a gatekeeper, parse incoming data, validate it, and then dispatch it to a model to be transformed. The result of the transform then returns back to the controller where you handle the reverse side of the API (ie. sending it back out in a web page, SOAP response, etc.). Pretty simple really.

      Views just complicate the whole thing and are really less architectural. Think of them as Smarty tagged pages.

  • Nice article I’ve recently got into MVC and it’s so better and cleaner to work with. The framework I use is also Codeigniter so easy to install and use, for both small and large projects.

  • Kohana > Code Igniter :) :)

  • Jono

    Never ever (ever!) use $_POST.
    Its always $this->input->post()

    • I take it $this->input is sanitized?
      (For those still using POST or GET outside of Intro Articles and Tutorials, search “SQL injection”. Assuming $this->input is sanitized, that’s a lot of heavy lifting done for you already! [Which is the point of a framework :] )

  • There’s a wealth of further info in the Forums at Codeigniter dot com. Well worth a visit. There’s a Wiki there too.

  • Tac

    Thanks for the article. We switched to CodeIgniter about a year ago, and it’s been great. I highly recommend using Smarty or Twig for your views. Makes a world of difference.

    Although I quite like CI, we’re now switching to Symfony2 for even more sophisticated applications, but there’s a steep learning curve. But now that we’ve bought into MVC it makes the evolution pretty natural.

  • Dorsey

    In my experience, CodeIngiter is probably not the best choice as a learning tool because it’s complication and has a huge execution overhead. Selecting a bare-bones MVC framework like SevinKevins would have been much better.

  • Destrehan Dave

    Thanks for the demo… anybody up to ‘translating’ this to or C# Using VS 2008 or 10?


  • Anne-Mie

    Anyone worked with Kohana? a fork of Codeignitor.

  • Nice article, just a note though: CI moved the application folder out of the system folder when version 2 was released. So you’ll find the application folder next to the system folder, not in it, “system/application”, like stated in the article.

  • Squirell

    Thanks for the tutorial. I’m also torn between ‘modifying the wheel’ i.e. creating my own small MVC framework or learning one of those out there (currently considering Yii Framework). Could you do an article on the pros and cons of building one’s own MVC Framework? Thanks

  • thanks for the post…!

  • Dakota

    This is the best advice in the codeigniter game right now.

  • Thank you for this great article. I’m just learning right now MVC so this really help me to understand how MVC works and i’m sure this will help me on my first project.

  • Ajay

    Thanks for help

  • Mike

    I was searching for easy tutorial of CI and found here, thanks a lot to be a starter.

  • Hello Stephen , a great article from you. can you post one more article regarding simple blog project in CI? waiting for your post….

    Thank you again

  • Pankaj

    Very nice tutorial or beginners !!!!



  • Thank you very much Stephen.. !!! Nice tutorial….

  • Excellent job… I was wondering if anyone has made changes to this code in order to retrieve data. For example type the name of the person and get the record details.. My plan is to expand this to location so I can search on location and I get all people living in LONDON. I have made changes to the table that’t an issue … I have problems writing the search code. Thx for any help or suggestions.

  • I need some help to put this code in MVC any help would be appreciated. It is a simple form which retrieve data from an SQL DB.. it works fine as one PHP file but I have problems to put it in MVC.

    Search Contacts Details
    You may search either by first or last name


    if(preg_match("/[A-Z | a-z]+/", $_POST['name']))


    //-query the database table
    $sql="SELECT * FROM Contacts WHERE FirstName LIKE '%" . $name . "%' OR LastName LIKE '%" . $name ."%'";

    //-run the query against the mysql query function

    //-create while loop and loop through result set

    $FirstName =$row['FirstName'];

    //-display the result of the array

    //echo "n”;
    echo “” . “” .$FirstName . ” ” . $LastName . “n”;
    echo “$FirstName” . “&nbsp” . “$LastName” . “&nbsp” .”ID” . “&nbsp” .”$Email”;
    //echo “”;
    echo “Please enter a search query”;

  • Speedovic

    Search Contacts Details
    You may search either by first or last name

  • Vipul Patil

    simply superb work , I was facing issue with codeigniter as I am nebie to CI,i had tried tutorial from CI official site but it never worked infact no one answered my queries on forum. I was like frustrated,But you made me, Thanks alot!,In future Hoping for some more tutorials on CI…

    • Vipul Patil

      Sorry but just want add something, The controller file phpmasterform.php is having some error. yeah,last line is
      but it should be

  • I am getting the following error:
    A Database Error Occurred

    Error Number: 1146

    Table ‘login.addresses’ doesn’t exist

    INSERT INTO `addresses` (`first_name`, `last_name`, `email`) VALUES (‘Sohail’, ‘Barat’, ‘’)

    Filename: E:wampwwwCIsystemdatabaseDB_driver.php

    Line Number: 330

    can anyone tell me how to remove it ????

Get the latest in PHP, once a week, for free.