CodeIgniter Tutorial for Beginners

MVC stands for Model View Controller. The model view controller pattern is the most used pattern for today’s world web applications. At present, there is more than a dozen PHP framework based on MVC pattern. The MVC pattern separates an application in 3 modules: Model, View, and Controller.

  • The Model is responsible for managing the data.
  • The View is responsible for displaying the data provided by the model in a specific format.
  • The Controller handles the model and view layers to work together.

CodeIgniter is one of the most popular PHP framework and it follows the MVC pattern. Web Developer can be able to build full-featured web applications with CodeIgniter.
This tutorial is aimed to introduce the CodeIgniter framework and step-by-step setup & installation guide for the beginners. In this tutorial, beginners will be able to learn the CodeIgniter development process from the scratch and create a basic CodeIgniter application. Our step by step tutorial helps web developers to learn CodeIgniter quickly and easily.
We will focus on the following topics in this CodeIgniter Tutorial for Beginners.

  • Basic Configuration & Setup.
  • Controller, Model, and View creation.
  • Performing basic database queries using Query Builder.

CodeIgniter Basic Tutorial

Configuration & Installation:

  • Download the latest version of CodeIgniter framework from the official site.
  • Extract the zip file and rename the folder with your desired application name (For example “codeigniter”).
  • Upload the entire “codeigniter/” folder to your server (localhost server).
  • Right now if you open the base URL (http://localhost/codeigniter/) of codeigniter application on the browser, the following screen will appear.
    codeigniter-tutorial-for-beginners-before-configuration-codexworld
  • Open the application/config/config.php file in a text editor and set the base URL of your web application.
    • Specify the base site URL (http://localhost/codeigniter/) in $config[].
      $config['base_url'] = 'http://localhost/codeigniter/';
  • If you want to use a database, open the application/config/database.php file in a text editor and specify your database credentials in $db[].
    • hostname – Database host name.
    • username – Database username.
    • password – Database password.
    • database – Database name.
    $db['default'] = array(
        
    'dsn'    => '',
        
    'hostname' => 'localhost',
        
    'username' => 'root',
        
    'password' => 'db_pass',
        
    'database' => 'codexworld',
        
    '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
    );

Controller & View Creation:
Now we will create the new controller called Home and load our new view.

  • Create Controller: Go to the application/controllers/ directory and create a PHP file called Home.php. Open this Home.php file in text editor and create a class named Home and extends this class from CI_Controller.
    <?php 
    defined
    ('BASEPATH') OR exit('No direct script access allowed');

    class 
    Home extends CI_Controller {

    }

    Note that: The first letter of the file name should be uppercase and same with the class name.

  • Create View: Go to the application/views/ directory and create a view file (home_view.php) for Home controller. Open this home_view.php file and write some HTML code.
    <?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Welcome to My First CodeIgniter Application</title>
    </head>
    <body>
    
    <div id="container">
        <h1>Welcome to My First CodeIgniter Application!</h1>
        <div id="body">
            <p>If you would like to edit this page you'll find it located at:</p>
            <code>application/views/home_view.php</code>
    
            <p>The corresponding controller for this page is found at:</p>
            <code>application/controllers/Home.php</code>
        </div>
    </div>
    
    </body>
    </html>
    
  • Earlier a Home controller was created, open it again and create an index() method to adding logic to the controller. In the index() method, the view() function will be used to load view file (home_view.php).
    <?php 
    defined
    ('BASEPATH') OR exit('No direct script access allowed');

    class 
    Home extends CI_Controller {
        public function 
    index()
        {
            
    $this->load->view('home_view');
        }
    }
  • Routing: By default Welcome controller class is loaded on application load. Open the application/config/routes.php file text editor and specify the new controller class (Home) as default controller.
    $route['default_controller'] = 'home';

Our Home controller is now functioning. Point your browser to base URL (http://localhost/codeigniter/) to open the new home page.

codeigniter-tutorial-create-controller-view-routing-codexworld

CodeIgniter with Database

In this section, we will use the database with the CodeIgniter application. In this tutorial part, the images will be retrieved from the database and display into CodeIgniter application.

Before you get started to create CodeIgniter application with database, take a look at the file structure.

codeigniter-demo-project-file-folder-structure-codexworld

Create Database Table:
Before querying the database, create a new database with your desired name. Once done, create a table named “images” to store the file information. Run the following SQL to create images table in the MySQL database.

CREATE TABLE `images` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `uploaded_on` datetime NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Upload Images:
Create a directory (uploads/) into the CodeIgniter’s root to store the image files. For testing purpose, insert some images into this directory and the file names in the images table of the database.

INSERT INTO `images` (`id`, `name`, `uploaded_on`) VALUES
(1, 'image1.jpg', '2017-09-28 10:30:00'),
(2, 'image2.jpg', '2017-09-28 10:30:00'),
(3, 'image3.jpg', '2017-09-28 10:30:00'),
(4, 'image4.jpg', '2017-09-28 10:30:00'),
(5, 'image5.jpg', '2017-09-28 10:30:00');

Connect Database:
To connect and access the database, you need to configure your database by specifying the database hostname, username, password, and name in the application/config/database.php file. Open the application/config/database.php file and set the following values.

$db['default'] = array(
    
'dsn'    => '',
    
'hostname' => 'localhost',
    
'username' => 'root',
    
'password' => 'db_pass',
    
'database' => 'codexworld',
    
'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
);

Create Model
Instead of writing database queries in the controller, it should be placed in a model. Models are the place where all the database related operations (retrieve, insert, update, delete, etc.) are done.

  • Open the application/models/ directory and create a new file called Home_model.php and add the following code.
  • Create a class (Home_model) and extend this class from CI_Model. Keep in the mind that the class name (Home_model) should be same of the file name (Home_model.php).
  • Load the database library, this will make the database class available through the $this->db object.
  • Create a method for retrieving the data from the database. For this example, get_images() method is defined to fetch the images from the database.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class 
Home_model extends CI_Model {
    public function 
__construct()
    {
        
$this->load->database();
    }
    
    public function 
get_images()
    {
        
$query $this->db->get('images');
        if(
$query->num_rows() > 0){
            
$result $query->result_array();
            return 
$result;
        }else{
            return 
false;
        }
    }
}

Display Images from Database:
The model has been set up, now it will be tied to the views that display the images to the users. This will be done in our Home controller created earlier.

Open the application/controllers/Home.php file and make the following changes.

  • At first, define the __construct() method, it calls the constructor of its parent class (CI_Controller) and loads the Home model.
  • Next, there is one method called index(), it gets images from the database using model’s get_images() method and passes the images data to view.
<?php
defined
('BASEPATH') OR exit('No direct script access allowed');

class 
Home extends CI_Controller {
    public function 
__construct()
    {
        
parent::__construct();
        
        
//load model
        
$this->load->model('home_model');
    }
        
    public function 
index()
    {
        
//get data from the database
        
$data['images'] = $this->home_model->get_images();
        
        
//load view and pass the data
        
$this->load->view('home_view'$data);
    }
}

Open the previously created application/views/home_view.php file and write the following codes to display all images which are passed from the controller.

<div class="gallery">
    <ul>
    <?php foreach($images as $img): ?>
        <li><img src="uploads/<?php echo $img['name']; ?>" /></li>
    <?php endforeach; ?>
    </ul>
</div>

Now point your browser to homepage URL (http://localhost/codeigniter/), the images will appear on the screen.

codeigniter-tutorial-controller-model-view-database-codexworld

CRUD Operations in CodeIgniter with MySQL

Example CodeIgniter Application

You can download the example CodeIgniter project which has created by following this tutorial. Only some minimal configuration needed to install this demo CodeIgniter application on your server. You only need to download the demo project from the source code link, extract the zip file and follow the instructions given in the ReadMe.txt file.

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

54 Comments

  1. Sahebrao Yammalwad Said...
  2. Giusi Said...
  3. Sharaf Said...
  4. Shilpi Singh Said...
  5. Sonkar Sunil Said...
  6. Praveen Said...
  7. Neha Said...
  8. Sandy Said...
  9. Gaurav Said...
  10. Ronak Said...
  11. Bhupatsinh Said...
  12. Hnin Wai Said...
  13. Karishma Said...

Leave a reply

keyboard_double_arrow_up