Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login

You must be logged to download. Click here to login


MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation


MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Developing Web Pages with PHP CodeIgniter

In this article, we are going to learn CodeIgniter and model-view-controller (MVC) web development and all the concepts that involves it.

In this article, we are going to learn CodeIgniter and model-view-controller (MVC) web development. But before diving into these concepts, let’s start with the basic question: why do we need it? When you develop your first PHP project you will notice that it consists of the following components:

  • A series of PHP pages, SQL queries and HTML.
  • There will be some JavaScript and CSS files for linking to pages.
  • Some files like header, footer, and database linkers.
After long time, if you want to make some modifications in your first project, you will face some confusion, because you will not remember your entire work. Although your project look modular, as you have made classes and included them into the pages but still you will face problems i.e. you had to review your project from scratch so that you will be aware of all your pages and database links. So to make programmer life easier, there is a way to solve this problem and it is called MVC. With MVC, developer can divide the entire code into distinct parts, which will make the entire application easier to develop, maintain and reconstruct. Moreover, MVC framework is very well structured and helps the developer concentrate on what’s important to client and project. So CodeIgniter is based on MVC framework and provides a systematic approach of coding for its user.

What’s Model-View-Controller?

As the name applies, it’s a design pattern that divides the code into three sections and helps the developers.
  • Model: maintains data i.e. all database related work is performed here.
  • View: for displaying data to user.
  • Controller: logics are applied here for handling models and views.
From Figure 1, it is clear that MVC takes into account the user. It begins with user. It is the user who clicks on a link or submit a form. It’s the controller which takes the necessary action i.e. manipulating data in Model and updating the View.

Figure 1. Illustration of working of MVC.

Note: you can create multiple views, and controllers for any given model with forcing changes in the model because of MVC three part separation.

Another way is to map it like this:

  • Model = Processing.
  • Output = View.
  • Controller = User input and traffic controller.

PHP MVC Frameworks

Looking at CodeIgniter, CakePHP and Symfony, you will find few similarities, as they are based on MVC framework. For example
  • They will allow you to use view for displaying of data, models that bind to a data source and controller that will monitor user action and will allow updates of model and views.
  • They use configuration files to help you maintain metadata, such as location of database, base URLs, and the like.
  • Allow you to extend the core code and build your own libraries and helper functions.

Why CodeIgniter Framework

CodeIgniter is very light weight and doesn’t force any convention but provides an important set of features through a set of built in libraries. Moreover, it has a low learning curve and provides an easy documentation style. In CodeIgniter all of your work will be in controller. That’s where you will load libraries, extract data from models, and pull it in view for displaying. So let’s start our work from the very beginning.

Downloading CodeIgniter

You can download latest version of CodeIgniter. At time of writing this article, I have downloaded the latest version i.e. CodIgnator-3.0.0. Your file will be downloaded in ZIP format so unzip it and push it into your development server, in our case we will save it in “htdocs” folder of “xampp”.

A short view on CodeIgniter

Opening your CodeIgniter you will see its file structure as shown in Figure 2. Opening the folder CodeIgnitor-3.0.0 in any text editor you will see four files and three subfolders.

  • Application
  • System
  • user_guide
  • index.php
  • license
  • readme.rst

“” and “readme.rst” are related for information of user so it’s better to have a look at these files.

The “license.txt”, contains CodeIgniter license agreement while “index.php” is a file, which is also called front end controller and basically routes traffic into the rest of application.

Figure 2. How CodeIgniter looks when opened in text editor.

Now let’s explore subfolders.

The application/Folder

The application folder contains the application you are building and consists of your Models, Views, Controllers and some other code. It’s the application folder where you will do 99% of your project work. Expanding this folder, you will find subfolders. Let’s gave a touch to each of them.




This folder contains all cached pages of your application you are building. We will explore it further in our later tutorials.


Config folder contains several PHP files that will control your configuration options. It contains files that will manage your database setup and other variables, which CodeIgniter needs to know i.e. base URL, libraries and helpers to auto load, etc. We will also look at important files necessary for configuration with in this tutorial.


This folder contains the controller you create for your application.


If you want, to swap any of the core system classes with your own version or even extend the core version, simply place your version inside this folder.


You can use your own helpers or extend standard ones, but they will be stored here to keep them separate from standard ones.


The hooks folder contains any hooks, you created, for your application. It’s CodeIgniter functionality and provide a means to tap into and modify the inner working of framework with hacking the core files.


When you create or incorporate your ownlanguagefiles, as needed, in order to provide application-specific error and other messages, or to provide translations of the core messages into otherlanguages.Such language files are stored here.


Contains custom libraries you create for your application.


The folder to which CodeIgniter writes errors and other logs. This need to be writable if you enable logging.


Contains model you created for you application.


Contains third party libraries, you use in CodeIgniter


Contains view you create for your application.

What is the purpose of index.php and .htaccess file in CodeIgniter


The purpose of this file is to prevent the contents of the directory from displaying if directory listing is enabled on your server. Apache servers by default have directory listing enabled. There are several instances which are given the right circumstances; you might be able to attempt to browse to a folder directly. These would mainly be caused by a server which is not configured properly, or an exploit. Therefore it is really best if you just leave the index.html files alone (they aren't hurting anything and they don't take up that much space). And it will be even better if you also add index.html file to any and all folders which you create.


.htaccess, is a configuration file for use on web servers running the Apache Web Server software. When an .htaccess file is placed in a directory which is in turn 'loaded via the Apache Web Server', then the .htaccess file is detected and executed by the Apache Web Server software. These .htaccess files can be used to alter the configuration of the Apache Web Server software to enable/disable additional functionality and features that the Apache Web Server software has to offer. These facilities include basic redirect functionality, for instance if a 404 file not found error occurs, or for more advanced functions such as content password protection or image hot link prevention.

'.htaccess' is the filename in full. It is not a file extension. For instance, you would not create a file called, 'file.htaccess', it is simply called, '.htaccess'. This file will take effect when placed in any directory which is then in turn loaded via the Apache Web Server software. The file will take effect over the entire directory it is placed in and all files and subdirectories within the specified directory.

You can create an .htaccess file using any good text editor such as TextPad, UltraEdit, Microsoft WordPad, and similar applications (you cannot use Microsoft NotePad).

The system/Folder

The system folder is where all core files of CodeIgniter lies. Expanding this folder consists of various subfolders that are described in the table.




Contains a list of core system files that are invoked every time CodeIgniter runs. You can extend these core files and if you want to use your own core or replace the existing ones, you can but you had to save it in application/core.


Contains core database drivers and other utilities.


Contains font related info and utilities.


This folder contains standard CodeIgniter helpers such as URL Helpers, Cookie Helpers and File Helpers etc. You will make frequent use of various helpers in your career.


Contains standard CodeIgniter libraries such as session library, file uploading library, and calendar library etc.


The files in this directory (system/language/english/) define the regular messages, error messages, and other generally output terms or expressions, for the different parts of the CodeIgniter framework.

CodeIgniter libraries

Various built-in libraries are present in CodeIgniter to help you do your work efficiently and in a fast way. Each library is a PHP class, with various methods, and can be used only by loading the particular library in controller.

CodeIgniter consists of following libraries:

Benchmarking class.

The benchmarking class is always active and there is no need to do it manually. This class is used to determine time difference between any two marked points in code and to calculate memory.

Calendaring class.

This class is used dynamically to create calendars for months and years, with providing formatting support also. It must be loaded by controller if you want to use.

Shopping cart class

This class provide shopping cart functionality and permits items for adding, updating and removing.

Config class

This class is used to retrieve configuration information and is initialized automatically by the system.

Email class

This class consists of a set of tools that simplifies the job of sending e-mails. It must be loaded, if you want to use it.

Encrypt class

The encrypt class must be loaded. It provides you with two-way data encryption and uses Mcrypt PHP extension, which is required for encrypt class to run.

Encryption library

The encryption library provides two-way data encryption. It uses PHP extensions that are not always available on all systems, so you must meet one of the following dependencies in order to use this library:

  • OpenSSl (and PHP 5.3.3)
  • MCrypt

If any of the above dependencies is not met, you will not get enough implementation to meet high standards required for proper cryptography.

File uploading class

The file uploading library allows you to handle file upload. It includes validation features and this library must be loaded, if you want to use it.

Form validation

This library will provide support for your form validation and must be loaded in order to use it..

FTP class

This class will support you to transfer files to remote server and must be loaded in order to use it.

Image Manipulation class

The image manipulation class must be loaded and help to resize images, thumbnail creation, image cropping, image rotating and image watermarking.

Input class

The input class must be loaded and it pre-processes global input data for security and provides helper functions for fetching input data and processing it.

JavaScript class

This library helps you certain common functions that you may want to use with JavaScript.

Language class

This library must be loaded and is used for loading different sets of language files for internationalization.

Loader class

The Loader library is automatically loaded. You will use this library primarily to load views with your controller, but it is also used to load libraries.

Migration class

This class will help you to alter your database in a structures and organized manner.

Output class

This library is automatically loaded and has one main function i.e. to send the finalized web page to the requesting browser. It is also used for caching.

Pagination class

This library must be loaded and is used for pagination of database results. You can control how many records should be displayed per page, how many records be pulled from database.

Template parser class

This library must be loaded and is used to create templates that contain parsable pseudo templates.

Security class

This library must be loaded and is used to handle some security functions such as guarding against XSS attacks.

Session library

This library must be loaded and is used to maintain state information about user.

HTML table class

This library must be loaded and is used to auto generate HTML tables from arrays or database results sets.

Trackback class

This library must be loaded and is used to send and receive Trackback data.

Typography class

This library must be loaded and helps you to format text.

Unit testing class

This library must be loaded and is used for unit test functions in your application.

URI class

The URI class library is automatically loaded and you will use this library when you are parsing URLs, breaking them into segments that can be passed to a controller or saved as variables.

User agent class

This library must be loaded and is used to identify the browser, mobile device, or the bot visiting your site. This library can also be used to detect supported languages, character sets, and referrers.

XML-RPC and XML-RPC server classes

This library must be loaded and is used to set up XML-RPC clients and servers.

Zip encoding class

This library must be loaded and is used to create ZIP archives of both text and binary data.

Up to this point, it would be pointless to cover each of the libraries in details. We will discuss database and session libraries in detail which will be used in our project.

Database library

CodeIgniter comes with a database library and contains a series of helpful functions that make it easy for you to create and run queries, and process the result set from those queries. Let’s have a look that what we can do with help of this library.

The first thing about database library in CodeIgniter is that it allows passing simple SQL queries.

Listing 1: Using query function to submit a query

$this->db->query('YOUR QUERY HERE');

In Listing 1, we use a function query( ), which when executes returns a database result object. So when “read” type queries are run you can use this object to show your results. And when “write” type queries are run, this function will return TRUE or FALSE depending upon success or failure of query. Also when you want to retrieve data, you will have to assign your query function result to your own variable, as shown in Listing 2.

Listing 2: Retrieving results of query.

$query = $this->db->query('YOUR QUERY HERE');

Simplified queries

The simple_query method is a simplified version of the $this->db->query( ) method. This function simply lets you submit a query. It doesn’t return a database result set, nor does it set the query timer, or compile bind data, or store your query for debugging. For example

Listing 3: Using simple_query function, for query running.

if ($this->db->simple_query('YOUR QUERY'))
        echo "Success!";
        echo "Query failed!";

Listing 3.will return a success or failure message upon executing.

How to return record set of a query using result( ) or result_array( ) methods.

To loop over the result set of a query, you can use two methods i.e. result( ) or result_array( ). It depends on whether you want to process your results as an object or as an array.

Listing 4: Processing query results through result( ) and result_array( ) methods.

$query = $this->db->query("YOUR QUERY");
foreach ($query->result() as $row)
        echo $row->title;
        echo $row->name;
        echo $row->body;
// Here is the alternative approach
foreach($query->result_array( ) as $row){
echo $row[‘title’];
echo $row[‘name’];
echo $row[‘body’];}

In Lisitng 4, we passed a query to query( ) function, and the result is assigned to a variable $query. We used foreach array, in which the result( ) function is accessed through $query object, and the result of each iteration is assigned to $row, and is displayed. Also we used the alternative method, for fetching result of query using result_array( ) function. This function will return a pure array. If nothing was found, the result is a null array. Again, the return array is assigned to $row variable in foreach loop, and then it is displayed.

Use of num_rows( ).

The num_rows( ) method will return count of rows, when a query is processed. For example

Listing 5: Using num_rows( ) to return a count of rows.

$query = $this->db->query('SELECT * FROM my_table');
echo $query->num_rows();
if( $query->num_rows( )>0){
foreach ($query->result() as $row)
        echo $row->title;
        echo $row->name;
        echo $row->body;

In Listing 5, we directly wrote query in query( ) function, and then num_rows( ) function, is used to display number of rows. Also an if statement, for checking if number of rows is greater than 0, will run foreach loop and will display the result of query.

Use of row( ) and row_array( )

If your query has only one row use row( ) method and if there are multiple rows of a query result, then use row_array( ) function. Depends on your choice you can also use row_array( ) method for single query results also. Result is returned as an object by row method while row_array( ) return result in an array form. For example

Listing 6: Displaying results of query using row( ) and row_array( ) method.

$query = $this->db->query('SELECT * FROM my_table');
if( $query->num_rows( )==1){
$row=$query->row( );{
        echo $row->title;
        echo $row->name;
        echo $row->body;
else {
$row = $query->row_array();
        echo $row['title'];
        echo $row['name'];
        echo $row['body'];
$row = $query->row_array(5); 
In Listing 6, a query is executed and the result is return to an object. After that we used if-else statement. We used a function num_rows( ) and if number of rows, returned by query is equal to 1, row( ) function will be executed and the result will be assigned to $row variable. Else in case of multiple rows, the row_array( ) function will be executed and the result will be assigned to $row variable but this time, you will have to write $row[‘name’], as the result is returned by query in array form.

Active Records or Query Builder class

CodeIgniter gives you access to a query builder class. You will take advantage of active record patterns as each of the pattern allows you to interact with a database table with minimal scripting. And thus help us to type less and makes database code more portable between database types. For example Listing 7: Query to retrieve all the database records from table.
$query= $this->db->get(‘table_name’);
//Alternate form
SELECT * from table_name;

In listing 7, we used $this variable, with the help of which we accessed the object db, and then through that object, we run the function get( ) with table name as a parameter. Don’t get confuse about $this variable and db object here, as they become available when you auto load database library and extend codigniter model i.e. CI_Model. At end of listing 7, alternate form of query is also written.

Note: table_name is used as general and you can replace it with real table name.

Limiting your records to retrieve from table

If you want to limit how many records to retrieve from the table, you can do it in an easy way using active records. For example

Listing 8: Limiting records from table

//it’s alternative query will be
// SELECT * from table_name limit 20,10;

Listing 8 is similar to Listing 6, only we passed extra parameter to get( ) function. The extra parameters are used for limiting purpose and will show 10 records after an offset 20 (records21-30).

Use of select( ) method

If you want to limit which fields are selected in your query, use the select method. For example

Listing 9: Selecting particular fields from your query.

$this- > db- > select(‘title, name, data’);
$Q = $this- > db- > get(‘table_name);

In Listing 9, we used a method select( ) ,and passed three parameters to it, which we want to retrieve from our table. Executing this query will show the selected fields.

Use of from( ) method

You can use from( ) method to tell the CodeIgniter which table to select from. For example

Listing 10: Selecting table using from method.

$this- > db- > select(‘title, name, data’);
$this- > db- > from(‘table_name’);
$Q = $this- > db- > get();

In Listing 10, we passed fields name to select( ) method and used from( ) method for selecting table to display data from. After that get( ) function is called to retrieve data from table.

Use of where( ) method

You can use where( ) method to set a condition. Also if you use multiple function calls they will be chained together with AND between them. For example

Listing 11: Using where( ) for setting condition.

$this- > db- > select(‘id, name, data’);
$this- > db- > from(‘table_name’);
$this- > db- > where(‘id’, 14);
//$this- > db- > where(‘id > =’, 9);
//$this- > db- > where(“name=’zohaib’ and id > 9”);
$this- > db- > where(‘data_type’, ‘secure’);
$Q = $this- > db- > get();
//It’s alternative query will be:
//select id, name, gender from persons where id=14 and data_type=’secure’

In Listing 11, we used select( ) method for selecting of fields from table, and where( ) method for setting conditions. We set various parameter of where( ), some forms of them are commented for understanding purpose. Note we leaved two where( ) methods uncommented, so there should be AND between them. Upon executing the code, will display the output. Alternate form of query is also present in comments form for understanding purpose.

Use of like( ) method.

For searching purpose, like( ) method is available. For example

Listing 12: Searching particular name from table using like( ) method.

$this- > db- > select(‘id, name’);
$this- > db- > from(‘table_name’); 
$this- > db- > like(‘name’, ‘zohaib’);
$Q = $this- > db- > get();
//alternative query becomes:
//select id,name from table_name where name like ‘%zohaib%’

Listing 12 is simple only we used like( ) function for searching purpose, to which we passed two parameters. One is field name of table, and the other is name of a person in that field of table.

Use of insert ( ) function

When you want to insert record into a table, you must have to make a data array, and then pass it to insert( ) method. In most cases the data array consists of information from a table but it could also contain data from a Cookie or session. For example

Listing 13: Using insert( ) to insert data into table.

$data = array(
        'title' => 'My title',
        'name' => 'My Name',
        'date' => 'My date'
$this->db->insert('mytable', $data);
// it’s alternative query will be:
 INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date')

In Listing 13, we made an array and then assigned it to $data variable. After that we passed that variable $data, and table name as a parameter to insert( ) function. Executing this will insert arecord into mytable. Alternate form of query is also written for understanding purpose and is present in comment form.


We have covered the basic file structure of CodeIgniter, how MVC works, what are the functionalities of application and system folder in CodeIgniter. Also we learnt which types of built-in libraries are present in CodeIgniter. Although a lot of libraries are present, but we just covered datatbase library in detail, as it’s the basic library and we will need it in our every project. In our next tutorial we will cover initial configuration of CodeIgniter, session library helpers, and maybe it’s possible that we will start our project, using CodeIgniter in that tutorial also.

Software developer doing B.E in Computer Science at Hamdard university karachi. Have good skills in php, html, javascript and css.

What did you think of this post?
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!

> More info about MrBool Credits
You must be logged to download.

Click here to login