November 5, 2014 2:23 am

Code your First CodeIgniter application

Welcome back to our CodeIgniter series. After our first two articles, Why Codeigniter Framework is Better than Custom PHP Development and How to install and Configure CodeIgniter Framework, its time to go on coding our first application using the famous framework. In this tutorial we will be coding a simple application using CodeIgniter’s MVC structure and connecting it to a MySQL database.

Code your First CodeIgniter application

MVC in CodeIgniter at a glance

Let’s explain how the Model-View-controller structure in CodeIgniter works. To create a new page, you should create a new class in application/controllers folder extending the core controller class CI_Controller. Each controller function could be accessed as a page, like, http://yoursite.com/index.php/ClassName/FunctionName.

To create a model which contains database operations, you should create  a new class in application/models folder extending the core model class CI_Model. The model can be loaded into controller using $this->model->load(‘model_name’) function and any model function can be called after loading the model using $this->model_name’->function_name().

In the views, you should put all the presentation code. Like HTML, CSS and JavaScript code. It’s not practical to put all the CSS and JS code in the views but we will be using this for now and get into the best practices later. The views should be placed in application/views folder. A view can be loaded into a controller using $this->view->load function.

Note: The view code is echoed to the controller when you load one. So be careful not to echo anything in a controller unless it is necessary.

You can include helpers which are built in CI in order to help you code less and save effort for rapid development. You can also load built in or third-party libraries. We will get into this in later tutorials.

This was a foundation for CI development. Now, let’s go on coding our first application using CI.

The Controller

To make a new page we will create a controller called Php_gang_ci with a function called first_app_tut. In this function we load some data from the database and send this data to the view in order to present it to the visitors. Continue reading to see the contents of the functions that we call here.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Php_gang_ci extends CI_Controller
{
    function __construct()
    {
	parent::__construct();
    }
    
    public function index()
    {
        
    }
    
    public function first_app_tut()
    {
    	// Load the database driver
	$this->load->database();
    	// Load the model
    	$this->load->model('PHP_gang_ci_model');
    	// Call the model function
    	$data['data_to_display'] = $this->PHP_gang_ci_model->data_grabber();
    	// Load the view. The second parameter is the array of variables sent to the view
    	$this->load->view('PHP_gang_ci_view', $data);
    }
}

To make this controller default, you should edit the array value in the application/config/routes.php file as follows. The index() method then will be the homepage for your site.

$route[‘default_controller’] = “php_gang_ci”;

The Model

 First, we will create a database using PHPMyAdmin or you can use you favorite MySQL administration tool. For this tutorial we will work on a database called php_gang_ci_toturial with a username: phpgang and a password: phpgangpass.

Run the following SQL statement to create a table in the newly created database.

CREATE TABLE IF NOT EXISTS php_gang_ci_toturial.php_gang_ci_table (
            id int(12) NOT NULL AUTO_INCREMENT,
            site varchar(50) COLLATE utf8_unicode_ci NOT NULL,
    		description varchar(500) COLLATE utf8_unicode_ci NOT NULL,
            PRIMARY KEY (id)
            );

Then, run the following SQL statement to enter the records that we want to load in the page.

INSERT INTO `php_gang_ci_toturial`.`php_gang_ci_table` (
`id` ,
`site` ,
`description`)
VALUES 
(NULL , 'phpgang', 'The best php site everr'),
(NULL , 'facebook', 'a social network');

To make you application connect to a database you should enter the connection info to the database.php file in application/config folder.

$db['default']['hostname'] = 'localhost'; // or your hostname if it's different
$db['default']['username'] = 'phpgang';
$db['default']['password'] = 'phpgangpass';
$db['default']['database'] = 'php_gang_ci_tutorial';

Now the database configuration and data are ready. We will create a model class called PHP_gang_ci_model in the application/models folder and create a method called data_grabber. Remember that we called those methods in the controller.

class PHP_gang_ci_model extends CI_Model
{
    function __construct()
    {
        parent::__construct();
    }
    
    function data_grabber()
    {
    	$result = $this->db->get('php_gang_ci_table');
    
    	return $result;
    }
}

The View

It’s time to make the data readable to the user. We will create the php_gang_ci_view view that we previously called in the controller.

<html>
	<head>
		<title>PhP Gang Page</title>
	</head>
	<body>
		<table>
			<tr>
				<th>
					Site
				</th>
				<th>
					Description
				</th>
			</tr>
			<?php 
			if(!empty($data_to_display->result_array()))
			{
				foreach ($data_to_display->result_array() as $row)
				{
					echo '<tr>';
					echo '<td>' . $row['site'] . '</td>';
					echo '<td>' . $row['description'] . '</td>';
					echo '</tr>';
				}
			}
			else 
			{
				echo 'The Database table is empty';
			}
			?>
		</table>
	</body>
</html>

Now it’s done. Yo can check your site using this link http://yoursite.com/index.php/php_gang_ci/first_app_tut and see the results. If you have any questions post a comment and I be available to answer your inquiries.

Author Amr Abdou

A full-stack web developer, Linux enthusiast, freelance tech writer & open-source supporter. Loves finding quit corners in public places or cafes accompanied by his laptop to try changing the world from there. You can check his latest works at social-evolvea.com or follow him on facebook, twitter, Linkedin or Google+


Tutorial Categories:

7 responses to “Code your First CodeIgniter application”

  1. filekh .com says:

    i want download

  2. Janardhan says:

    after executing error “object not found” is displayed

    • ProgrammingNewbie . says:

      probably because there’s an incorrect calling of the table in your model? Check the case of the name on the table.

  3. ProgrammingNewbie . says:

    Code Igniter is something powerful too, low foot print, look how easy it is to build an application!

  4. kp arora says:

    I have an query related to session , When I try to load $this->load->library(‘session’); in the controller file , construct function and try to set session, it will not works Please provide demo for sessions

  5. kp arora says:

    I have an query related to session , When I try to load $this->load->library(‘session’); in the controller file , construct function and try to set session, it will not works Please provide demo for sessions

  6. Janet Parker says:

    Thank you for the information.

Leave a Reply

Your email address will not be published. Required fields are marked *