CodeIgniter Basic With CRUD

 

CodeIgniter (CI) is one of popular php framework. If you are already building PHP Application, CodeIgniter will help you to do it better and more easily. With CodeIgniter, you can save time, make your web more robust, your code will be easier to read and maintenance. It is free, lightweight, and simple to install. In this post, we will know more deep about CodeIgniter before write code.
Nice, CodeIgniter is small and lightweight framework. You don’t need long time to download it. You can get it from http://www.codeigniter.com. CI was written by Rick Ellis, rock musician turned programmer.
With CodeIgniter, you can cut down the amount of code you need to type. This is not just good for lazy, but: less type, fewer mistake, and less time for spend debugging.
But, CodeIgniter is not everything. We will not find ‘engine generator’ that can build page self. Several frameworks have features like that. For example, they can create web page (that to do basic Create, Read, Update, and Delete operation) automatically. CodeIgniter doesn’t do this.
This, I copy from their help page: “Our goal for CodeIgniter is maximum performance, capability, and flexibility in the smallest, lightest possible package.
From a technical and architectural standpoint, CodeIgniter was created with the following objectives:

    Dynamic Instantiation. In CodeIgniter, components are loaded and routines executed only when requested, rather than globally. No assumptions are made by the system regarding what may be needed beyond the minimal core resources, so the system is very light-weight by default. The events, as triggered by the HTTP request, and the controllers and views you design will determine what is invoked.
    Loose Coupling. Coupling is the degree to which components of a system rely on each other. The fewer components depend on each other the more reusable and flexible the system becomes. Our goal was a very loosely coupled system.
    Component Singularity. Singularity is the degree to which components have a narrowly focused purpose. In CodeIgniter, each class and its functions are highly autonomous in order to allow maximum usefulness.

Nice feature, CodeIgniter is very flexible. We can apply at PHP 4.3.2 and above, or PHP 5.0 or above. CI support serveral database: MySQL, MySQLi, MS SQL, Postgre, Oracle, SQLite, and ODBC.

Preparing Database

We will learn about showing data from database in CodeIgniter. But, before that, we prepare a database for practice. This post create a database named “ci_test” and a table named “users”. We use phpMyAdmin for easy.

    Open your phpmyadmin.
    Enter database name “ci_test” in create new database field.
    Click Create button. Your database will be created.
    Create new table by running this query in your sql window:

    CREATE TABLE IF NOT EXISTS `users` (

    `id` int(11) NOT NULL AUTO_INCREMENT,

    `name` varchar(50) NOT NULL,

    `email` varchar(100) NOT NULL,

    `address` varchar(255) NOT NULL,

    `mobile` varchar(15) NOT NULL,

    PRIMARY KEY (`id`)

    ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=16 ;

    Insert some sample data to your users table by running this query in your sql window:


    INSERT INTO `users` (`id`, `name`, `email`, `address`, `mobile`) VALUES

    (1, 'Masud Alam', 'm@sud.com', 'ldsjfla lsdj lsdj flk', '9879879'),

    (2, 'Sohel Alam', 'al@m.com', 'Dhaka,Bangladesh,BD', '09080'),

    (8, 'Salim', 'salim.hossain@ebizzsol.com', 'test', '01717552181'),

    (9, 'Syed Salim', 'salimhossain@gmail.com', 'Gulshan, Dhaka', '01717552181'),

    (10, 'Salim Hossain', 'salimhossain@gmail.com', 'Gazipur-1700, Dhaka, Bangladesh.', '01717552181'),

    (13, 'Galib', 'g@lib.com', 'Dhaka,Bangladesh', '987979');
Showing All Data from your users table:

Now, we learn how to show data in CodeIgniter. As we know, CodeIgniter use MVC pattern. We will use Model for retrieve data from database.

First, build a model. Create a file named “users_model.php” within codeigniter/application/models. Enter following code:

    <?php

    class Users_model extends CI_Model {

    function __construct()

    {

    parent::__construct();

    $this->load->database("ci_test");

    }

    public function get_all_users()

    {

    $query = $this->db->get('users');

    return $query->result();

    }

    }

    ?>

Next, we make a view. Create a file named “show_users.php” within ci/application/views. Enter folowing code:

    <!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>CI CRUD</title>

    </head>

    <body>

    <h2> Simple CI CRUD Application </h2>

    <table width="600" border="1" cellpadding="5">

    <tr>

    <th scope="col">Id</th>

    <th scope="col">User Name</th>

    <th scope="col">Email</th>

    <th scope="col">Mobile</th>

    <th scope="col">Address</th>

    </tr>

    <?php foreach ($user_list as $u_key){ ?>

    <tr>

    <td><?php echo $u_key->id; ?></td>

    <td><?php echo $u_key->name; ?></td>

    <td><?php echo $u_key->email; ?></td>

    <td><?php echo $u_key->address; ?></td>

    <td><?php echo $u_key->mobile; ?></td>

    </tr>

    <?php }?>

    </table>

    </body>

    </html>

Build controller. Create a file named “users.php” within codeigniter\application\controllers. Enter following code:

    <?php

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

    class Users extends CI_Controller {

    function __construct()

    {

    parent::__construct();

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

    $this->load->model('users_model');

    }

    public function index()

    {

    $data['user_list'] = $this->users_model->get_all_users();

    $this->load->view('show_users', $data);

    }

    }

Now, try to point your browser to http://localhost/codeigniter/index.php/users/

Insert Data to our database using CodeIgniter

Now, we begin create a form for input data.

Create “insert.php” within codeigniter\application\views. Write following code:

    <!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>CI Insert Form</title>

    </head>

    <body>

    <form method="post" action="<?php echo base_url();?>index.php/users/insert_user_db">

    <table width="400" border="0" cellpadding="5">

    <tr>

    <th width="213" align="right" scope="row">Enter your username</th>

    <td width="161"><input type="text" name="name" size="20" /></td>

    </tr>

    <tr>

    <th align="right" scope="row">Enter your email</th>

    <td><input type="text" name="email" size="20" /></td>

    </tr>

    <tr>

    <th align="right" scope="row">Enter your Mobile</th>

    <td><input type="text" name="mobile" size="20" /></td>

    </tr>

    <tr>

    <th align="right" scope="row">Enter Your Address</th>

    <td><textarea name="address" rows="5" cols="20"></textarea></td>

    </tr>

    <tr>

    <th align="right" scope="row">&nbsp;</th>

    <td><input type="submit" name="submit" value="Send" /></td>

    </tr>

    </table>

    </form>

    </body>

    </html>

Now, we need to load Insert Form. Put at controller (users.php within codeigniter/application/controllers), add_form () method.

    public function add_form()

    {

    $this->load->view('insert');

    }

Now for insert data from our insert.php form to users table we need to create another method called insert_user_db() in our controllers with following code:

    public function insert_new_user()

    {

    $udata['name'] = $this->input->post('name');

    $udata['email'] = $this->input->post('email');

    $udata['address'] = $this->input->post('address');

    $udata['mobile'] = $this->input->post('mobile');

    $res = $this->users_model->insert_users_to_db($udata);

    if($res){

    header('location:'.base_url()."index.php/users/".$this->index());

    }

    }

Now add new method insert_users_to_db in your models
    public function insert_users_to_db($data)

    {

    return $this->db->insert('users', $data);

    }

Now, click your “Insert New User” link in your browser , you see your insert form like this:

CodeIgniter Insert Form

Ok. You can test it. Input some data to your insert form .

CodeIgniter Insert Form with sample data

Now, we create a method called getById() to get a single user information at our model

    public function getById($id){

    $query = $this->db->get_where('users',array('id'=>$id));

    return $query->row_array();

    }

After Create getById Method in our users_model, Now We Create edit Method to send a single user information to edit.php form as follows:

    public function edit(){

    $id = $this->uri->segment(3);

     $data['user'] = $this->users_model->getById($id);

    $this->load->view('edit', $data);

    }

Now we create edit.php form for update users:

    <!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>CI Insert Form</title>

    </head>

    <body>

    <form method="post" action="<?php echo base_url();?>index.php/users/update">

    extract($user);

    <table width="400" border="0" cellpadding="5">

    <tr>

    <th width="213" align="right" scope="row">Enter your username</th>

    <td width="161"><input type="text" name="name" size="20" value="<?php echo $name; ?>" /></td>

    </tr>

    <tr>

    <th align="right" scope="row">Enter your email</th>

    <td><input type="text" name="email" size="20" value="<?php echo $email; ?>" /></td>

    </tr>

    <tr>

    <th align="right" scope="row">Enter your Mobile</th>

    <td><input type="text" name="mobile" size="20" value="<?php echo $mobile; ?>" /></td>

    </tr>

    <tr>

    <th align="right" scope="row">Enter Your Address</th>

    <td><textarea name="address" rows="5" cols="20"><?php echo $address; ?></textarea></td>

    </tr>

    <tr>

    <th align="right" scope="row">&nbsp;</th>

    <td>

    <input type="submit" name="submit" value="Update" /></td>

    </tr>

    </table>

    </form>

    </body>

    </html>

After create edit form, now we add updating function.

First, create update_info () method at model “users_model.php”.

    public function update_info($data,$id)

    {

    $this->db->where('users.id',$id);

    return $this->db->update('users', $data);

    }

Then, create update() method at your controller “users.php”:

    public function update()

    {

    $mdata['name']=$_POST['name'];

    $mdata['email']=$_POST['email'];

    $mdata['address']=$_POST['address'];

    $mdata['mobile']=$_POST['mobile'];

    $res=$this->users_model->update_info($mdata, $_POST['id']);

    if($res){

    header('location:'.base_url()."index.php/users/".$this->index());

    }

    }
Deleting Data

Now, we create deleting function.

First, create a method delete_a_user() for deleting data at model.

    public function delete_a_user($id)

    {

    $this->db->where('users.id',$id);

    return $this->db->delete('users');

    }

Then, create a method for deleting data at controller:
view source
print
?

    public function delete($id)

    {

    $this->users_model->delete_a_user($id);

    $this->index();

    }