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, 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 frameworks and it follows the MVC pattern. Web Developer can be able to build full-featured web applications with CodeIgniter.
Today we will describe the CodeIgniter setup process for the beginners. In this tutorial, beginners would be able to learn the CodeIgniter development process from the scratch. Our step by step tutorial helps web developers to learn CodeIgniter quickly and easily.
Also, you can download the demo CodeIgniter project which we have been created at the time of describing this tutorial. You only need to extract the zip file and follow the instructions given in the ReadMe.txt file. If you wish to download the demo Codeigniter project, download it from the Download Source Code link at the end of the tutorial.

CodeIgniter Basic

  • Download the latest version of CodeIgniter from here: http://www.codeigniter.com/
  • Extract the zip file and rename the folder. For example codeigniter/.
  • Move the folder at the localhost.
  • If you try to open the home URL (http://localhost/codeigniter/), you’ll see the following screen at the browser.
    codeigniter-tutorial-for-beginners-before-configuration-by-codexworld
  • Open the application/config/config.php file and follow the below instruction.
    •  Set the $config['base_url'] variable value with your project base URL(http://localhost/codeigniter/)
  • If you want to use database table, then open the application/config/database.php file and follow the below instruction.
    •  Set $db['default']['hostname'] variable value with your database host name.
    •  Set $db['default']['username'] variable value with your database username.
    •  Set $db['default']['password'] variable value with your database password.
    •  Set $db['default']['database'] variable value with your database name.
  • Open the application/config/routes.php file and follow the below instruction.
    •  Change $route['default_controller'] variable value from "welcome" to "home". Or which you want to load the controller by default.
  • Go to the application/controllers/ directory and create a PHP file called Home.php. Open this Home.php file and follow the below instruction.
    •  At the beginning add the following codes for preventing the direct script access.
      <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
    •  Create a class named Home and extends this class from CI_Controller. Also, keep in mind that the class name and file name must be same.
      class Home extends CI_Controller {
      
      }
  • 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 for testing purpose.
  • Open the Home controller (application/controllers/Home.php) and add the following changes.
    •  Create a index() function.
    •  Load the view file into the index() function. The $this->load->view() statement is used for render the view.
      $this->load->view('home_view');
  • Refresh the homepage (http://localhost/codeigniter/) at the browser, you’ll see the view page as per the given HTML.
    codeigniter-tutorial-for-beginners-load-view-by-codexworld

CodeIgniter with Database

Now we will use the database with the CodeIgniter application. In this tutorial we will fetch the images from the database and display the images into CodeIgniter. Please follow the below steps.
  • Create a database at the PHP MyAdmin. Like the database name is "test". Once the database is created, then create a table named "images". Also you can copy the below table SQL and run this SQL to the database.
    CREATE TABLE `images` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `image` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
        `created` datetime NOT NULL,
        `modified` datetime NOT NULL,
        PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
  • Create a directory(uploads/) into the CodeIgniter root directory and insert some images into this directory. Now insert the images name at the "images" table to the database.
  • For database access we have to define the database hostname, database username, database password and database name in the database.php file. Open the application/config/database.php file and set the following values.
    $db['default']['hostname'] = 'localhost';$db['default']['username'] = 'root';$db['default']['password'] = '';$db['default']['database'] = 'test';
  • For use the database function we need load the CodeIgniter database library. We need to tell Codeigniter to auto-load the database library so we don’t have to ask for it every time we want to do a database query. Open the file application/config/autoload.php, go to the 55 line and make the below changes.
    •  Find $autoload['libraries'] variable and set array('database'); value at this variable.
      $autoload['libraries'] = array('database');
  • Create a model into the models directory. Follow the below steps:
    •  Go to the application/models/ directory and create the file Home_model.php.
    •  Create a class and extend this class from CI_Model class. The class name should be the same of the file name, means the class name would be Home_model.
    •  Create a function for retrieve the data from the database. For this tutorial purpose we declare the get_images() function, this function is used for fetch the images from the database.
    •  The whole Home_model.php file codes are given below.
      <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
      
      class Home_model extends CI_Model {
          function get_images()
          {
              $query $this->db->get('images');
              if($query->num_rows() > 0){
                  $result $query->result_array();
                  return $result;
              }else{
                  return false;
              }
          }
      }
  • Open the previously created application/controllers/Home.php file and make the following changes.
    •  Load the model: $this->load->model('home_model')
    •  Get images data from the model: $this->home_model->get_images()
    •  Store the images data into an associative array: $data[‘images’] = $this->home_model->get_images();
    •  Pass the images data to the view: $this->load->view('home_view', $data)
    •  The whole Home.php file codes are given below.
      <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
      
      class Home extends CI_Controller {
          public function index()
          {
              //load model
              $this->load->model('home_model');
              
              //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 some codes for display all images which are passed from the controller.
    <?php if(!empty($images)): foreach($images as $img): ?>    <li><img src="uploads/<?php echo $img['image']; ?>" alt=""></li>
    <?php endforeach; endif; ?>
  • The whole home_view.php file codes are given below.
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <title>Welcome to my first CodeIgniter application.</title>
    <style type="text/css">
        body {background-color: #fff;margin: 40px;font: 13px/20px normal Helvetica, Arial, sans-serif;color: #4F5155;}
        h1 {color: #fff;background-color: #FB4314;border-bottom: 1px solid #D0D0D0;font-size: 19px;font-weight: normal;margin: 0 0 14px 0;padding: 14px 15px 10px 15px;}
        #container{margin: 10px;border: 1px solid #D0D0D0;-webkit-box-shadow: 0 0 8px #D0D0D0;}
        .gallery{ width:100%; float:left; }
        .gallery ul{ margin:0; padding:0; list-style-type:none;}
        .gallery ul li{ padding:7px; border:2px solid #ccc; float:left; margin:10px 7px; background:none; width:auto; height:auto;}
    </style>
    </head>
    <body>
    <div id="container">
        <h1>Welcome to First CodeIgniter Application.</h1>
        <div id="body">
            <div class="gallery">
                <ul>
                <?php if(!empty($images)): foreach($images as $img): ?>               <li><img src="uploads/<?php echo $img['image']; ?>" alt=""></li>
                <?php endforeach; endif; ?>
                </ul>
            </div>
        </div>
    </div>
    </body>
    </html>
    
  • Refresh your browser again, homepage URL will show the following screen.
    codeigniter-tutorial-for-beginners-fetch-data-from-database-by-codexworld
 In the above tutorial has described the basic guide of CodeIgniter application. We’ll discuss the advanced

Comments