Pages

How to start with Codeigniter?

Friday, February 24, 2012
If you have an experience with PHP two or three project, you should speed up your coding time with CI. CI will give you more easy life with PHP. CI uses the Model View Controller architectural pattern which gives you great flexibility when it comes to reusing, altering and upgrading code. When I write this tutorial CI version is 2.0.2. It is little different form older version. Because It support PHP 5.1.6 and newer.

Requirement

CodeIgniter

Step 1: Configuration

Download CI latest version from its official site. You will get zip file. Extract it to your sever host and rename your folder as mycisite.
Inside our mycisite folder you will found three folder and two file. You don't need to touch any folder except application folder.Open your application folder. You will see many folder and two file. Now for this step open config folder and then open config.php with your favourite editor. In line 17 you will see this code

$config['base_url'] = '';

Add your site url between single quote like following

$config['base_url'] = 'http://localhost/mycisite/';

Now you can run your site. If you run your site, you will see like following

Why? Open the mycisite>application>config>routes.php. In line 41 you will see like this

$route['default_controller'] = "welcome";

CI call mycisite>application>controllers>welcome.php as a default controller because of above line. We will write a home.php as default controller so change the controller name as following

$route['default_controller'] = "home";

We will also do the configuration for database. So open mycisite>application>config>database.php. From line 44 you will see like following

$db['default']['hostname'] = 'localhost';
$db['default']['username'] = '';
$db['default']['password'] = '';
$db['default']['database'] = '';
$db['default']['dbdriver'] = 'mysql';
$db['default']['dbprefix'] = '';
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = TRUE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = '';
$db['default']['char_set'] = 'utf8';
$db['default']['dbcollat'] = 'utf8_general_ci';
$db['default']['swap_pre'] = '';
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;

We need to set the hostname, username, password and database. Before you set the database, you should create a database from phpmyadmin. I create a database name as cidata. So our database setting is like that

$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'your_username';
$db['default']['password'] = 'your_password';
$db['default']['database'] = 'cidata';

Step 2:Creating our database table

The database need just one table with just 4 fields id (int 10), name (varchar 50), email (varchar 50) and message (text). Import following SQL statement via phpMyAdmin or any other MySQL tool.

CREATE TABLE `message` (
`id` int( 10 ) NOT NULL AUTO_INCREMENT ,
`name` varchar( 50 ) NOT NULL ,
`email` varchar( 50 ) NOT NULL ,
`message` text NOT NULL ,
PRIMARY KEY ( `id` )
) ENGINE = InnoDB DEFAULT CHARSET = latin1 AUTO_INCREMENT =1;

Step 3:Calling Message Form View from Controller

Now it is time to write our home.php controller. Open a new file in your editor and then copy and paste following code and save this file as mycisite>application>controllers>home.php.

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

class Home extends CI_Controller{

    public function __construct(){
        parent::__construct();

    }

    public function index()
    {
        echo "Hello world!";
    }
}
?>

If you run the site you will see Hello world! in your browser. It means function index is the default function for our controller. Now obviously we don't actually want it to output "Hello World!" so we can go ahead and delete that and start building it up properly. So we will call the message form as a default.

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

class Home extends CI_Controller{

    public function __construct(){
        parent::__construct();

    }

    public function index()
    {
        $data['base']=$this->config->item('base_url');
        $data['title']= 'Message form';
        $this->load->view('header_view',$data);
        $this->load->view('messageform_view',$data);
        $this->load->view('footer_view',$data);
    }
}
?>

We need to set the value for the $data variable array. Firstly we set our base url as a base variable. The code of $this->config->item('base_url') will grab our url data from the application>config>config.php file. Another one is the title for our form view. You can use this data in the view file as a $base or $title. So we should pay the meaningful name in our $data variable array. Then we load three view files for our message form. Why is it three? Because header and footer will include every view file. So we should do as the separate file.

Step 4: Creating Message Form View

Open a new file in your editor and let's start our header_view.php. This file is very simple for our simple project.Below is our header_view.php. Save this view file as mycisite>application>view>header_view.php.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title><?php echo (isset($title)) ? $title : "My CI Site" ?> </title>
<link rel="stylesheet" type="text/css" href="<?php echo $base ?>css/style.css" />
</head>
<body>
    <div id="wrapper">

You will notice that our title is called dynamically. $title variable is from our $data variable array. Behind the scenes, CI makes good use of another PHP function: extract(). This takes each value in the $data array and turns it into a new variable in its own right -so the $data array that we have just define is receive by the view as a series of separate variables: $title, $base, and so on. We use the $base variable to call the style.css file. We need to create a css folder to put our css file separately. So create a folder under the mycisite folder name as css. We don't need to write the end tag for body, html, div wrapper because we will write this end tag in our footer_view.php file. Following is our footer_view.php. Save this view file as mycisite>application>view>footer_view.php.

</div><!--<div id="wrapper">-->
</body>
</html>

It is simple, isn't it?
Now let's start our messageform_view.php. Following is our messageform_view.php. Save this view file as mycisite>application>view>messageform_view.php.

<div id="content">
<?php $this->load->helper('form'); ?>
<?php echo form_open("home/insert_message"); ?>
    <p>
        <label for="name">Name: </label>
        <input type="text" name="name" id="name" value="" size="30" />
    </p>
    <p>
        <label for="email">E-mail: </label>
        <input type="text" name="email" id="email" value="" size="30" />
    </p>
    <p>
        <label for="message">Message: </label>
        <textarea name="message" id="message" value="" cols="50" rows="4"></textarea>
    </p>
    <p>
    <input type="submit" value="Submit" />
    </p>
<?php echo form_close(); ?>
</div><!--<div id="content">-->

Firstly we need to load the form helper because we will use the CI form helper for our html form. CI has many helper for you to reduce the coding and more flexible. You can also create your own helper. If you were using plain HTML code, you'd write:
<form method="post" action="http:/www.mysite.com/index.php/websites/update" />
Whereas, if you open your form with CI, you only need to use:
form_open(home/insert_message)

If you don't understand the action link, don't worry I will explain you later.

Note incidentally, that CI assumes your forms will always send POST data rather than GET data. CI makes extensive use of the URLs itself, so this avoids confusion.

At the end of the form you need to close the form with form_close(); function. Run your site. You will see the the message form.

Step 5: Creating the insert_message function for our Controller

In our home Controller, we need to add the insert_message() function for our form submitting. Following is our home.php with insert_message() function.

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

class Home extends CI_Controller{

    public function __construct(){
        parent::__construct();

    }

    public function index()
    {
        $data['base']=$this->config->item('base_url');
        $data['title']= 'Message form';
        $this->load->view('header_view',$data);
        $this->load->view('messageform_view',$data);
        $this->load->view('footer_view',$data);
    }
    public function insert_message()
    {
        $this->load->model('message_model');
        $this->message_model->add_message();
    }
}
?>

Firstly we load the model message_model(next step we will create this model). And then we call the add_message() function from our message_model model.

Step 6:Creating the message_model model

It is time to create our model. Following is our message_model.php. Save this model file as mycisite>application>model>message_model.php.

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

class Message_model extends CI_Model {

    public function __construct()
    {
        parent::__construct();
        $this->load->database();
    }
    public function add_message()
    {
        $data=array(
            'name'=>$_POST['name'],
            'email'=>$_POST['email'],
            'message'=>$_POST['message']
            );
        $this->db->insert('message',$data);
    }
}
?>

In our model constructor, we need to load the database library like:
$this->load->database();
CI also has many libraries. You can also learn from its user_guide inside our project folder.

Alternatively instead of loading the library in each individual model we can open autoload.php (system -> application -> config -> autoload.php) the first array we come across is the one which we want.
$autoload['libraries'] = array();
You need to put the names of each of the libraries you want in the array as single entites.
$autoload['libraries'] = array('database');
The second function is add_message() function. Remember we called the add_message() function from our controller to add our data into our database. Firstly we create the $data array. Left side is field names from our database and right side is names from our form. This line $this->db->insert('message',$data); will insert the data into our database. First parameter is our table name and second is our data. It is very to use, isn't it? Now you can run your site. If you submit the form, our data will insert into our database but our browser will be blank. So we need to redirect our site into somewhere. For this project I will redirect into our form page.

Step 7:Redirecting our page

To redirect our page, we need to call the url helper like this

$this->load->helper('url');

Now we can use redirect function like this

redirect("/home/index");

You only need to give the parameter for this function is controller name and function name. CI will do the rest. Now submit our form. You will see the form again and also fill with data into our database. Next step we will show the inserted data below the form like facebook.com.

Step 8:Creating get_all database function

To show our all message below the submit form, we need to grab all data from our database. Below function will grab the all data. Add this function to your model file.

public function get_all()
    {
        $query=$this->db->get('message');
        return $query->result();
    }

CI get() db function will grab all data from the message table. This function will return the result as an object. And then we will return the result object by using result() function. If you more prefer array form you can return array like following

return $query->result_array();

Step 9:Calling data grabbing function from our Controller

Firstly we need to load our model. And then we need to call the function that we have created already. When we call the function we need to set the return data to our data array. So following is our needed code

$this->load->model("message_model");
    $data['query']=$this->message_model->get_all();

We will add above code to the appropriate place. This place is before loading view. So our index function will be like following

public function index()
    {
        $data['base']=$this->config->item('base_url');
        $data['title']= 'Message form';
        $this->load->model("message_model");
        $data['query']=$this->message_model->get_all();
        $this->load->view('header_view',$data);
        $this->load->view('messageform_view',$data);
        $this->load->view('footer_view',$data);
    }

Step 10:Displaying message below our message form

Add the following code below your form closing function in your view.

<?php
foreach($query as $row)
{
?>
    <div>
        <?php echo $row->name; ?>: Says
    </div>

    <div>
        <?php echo $row->message; ?>
    </div>
    <br />
<?php
}
?>

This is a straight forward foreach loop looping through each of the object entities and echoing the message in our view. Now you can run your site. It will show the all message below the message form.

Step 11:Designing our site with CSS

Below is our css code for our site. Save this css file as mycisite>css>style.css.

@charset "utf-8";
/* CSS Document */
body{
    background-color:#FFF;
    font-family:Monaco,Consolas,'Lucida Grande','Lucida Console';
    font-size:16px;
    text-shadow:rgba(0,0,0,0.01) 0 0 0;
}
#wrapper{
    width:960px;
    margin:0 auto;
}
#content{
    width:620px;
    margin:5px;
    float:left;
}
.message_form{
    width:520px;
    padding:20px 20px 0px 40px;
    border:1px dashed #A0A0A4;
}
.name_field label, .mail_field label, .message_field label{
font-weight: bold;
}
.message_field label{
    float: left;
}
.name_field{
    width:250px;
    float:left;
}
.mail_field{
    width:250px;
    float:left;
}
.message_form input[type="text"]{
    width: 170px;
}
.message_form textarea{
width: 490px;
height: 70px;
}
.message_show{
    border-bottom:1px dashed #A0A0A4;
}

Run your site. Below is my screenshot. Next tutorial we will add Pagination.

Download Source Code

12 comments:

  1. Hello dear your tutorial seems to be fine but as i followed it exactly, throwing error "The requested URL /ci2.1/home/insert_message was not found on this server" MY path in url is "http://localhost/ci2.1/home/insert_message"

    y this is happening, i have tried some tricks but all in vain.

    regards,
    Nasir

    ReplyDelete
  2. http://localhost/ci2.1/index.php/home/insert_message

    ReplyDelete
  3. this is the most simple an real that I've written so far

    ReplyDelete
  4. easy to understandable script.
    thanks for sharing

    ReplyDelete
  5. in which file i can put the code of redirection to home page

    ReplyDelete
    Replies
    1. in the insert_message function (in the controller) add following two lines to redirect
      $this->load->helper('url');
      redirect("/home/index");

      Delete
  6. Very nicely written article, thanks a lot.

    ReplyDelete
  7. in which file i can put the following code :-
    public function get_all()
    {
    $query=$this->db->get('message');
    return $query->result();
    }

    ReplyDelete
  8. Thank you so much. Nice script . Easy to Understand.

    ReplyDelete
  9. Thanks for sharing the information. It is very useful for my future. keep sharing.

    Best Linux training in Noida
    Linux Training Institute in Noida

    ReplyDelete
  10. Superb blog I visit this blog it's extremely marvelous. Interestingly, in this blog content composed plainly and justifiable. The substance of data is exceptionally instructive.
    oracle fusion financials classroom training
    Workday HCM Online Training
    Oracle Fusion Financials Online Training
    Oracle Fusion HCM Online Training
    Oracle Fusion SCM Online Training
    Oracle Fusion HCM Classroom Training

    ReplyDelete