Basically CodeIgniter is one of the framework of PHP. CodeIgniter is created by EllisLab, but now it is a project of British Columbia Institute of Technology. It uses simple MVC (Model View Controller) pattern. It is coupled faster, flexible and high performance system. It supported databases such as MySQL, Oracle, MS SQL, SQLite etc...

  • Model: It contains database connectivity code ie. all types of queries. Means in the model you have to write only queries like Insert, update, delete, select etc…
  • View: It contains all view file which we can see on browser.
  • Controller: Controller is bridge between Model and View. In it you have to write all your logics. It gets data from model and display to the view files.

This blog will explain you how to perform CRUD (Create, Read, Update and Delete) operation (You can also say Insert, Select, Update and Delete operations) in PHP CodeIgniter.

I’m assuming that you created database and table for tbluser with columns UserId, UserName, UserEmail, UserPassword, UserGender, UserHobbies, UserProfile.

General setup steps for CodeIgniter project

1. Install CodeIgniter 3: You can simply download CodeIgniter from Download CodeIgniter 3. This will contains some folders whose work has been written in this blog.

2. base_url: First of all set base_url of your project. It located application->config->config.php.

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

3. database.php: Setup your database. It located application-> config-> databse.php. Here you have to set hostname, username, password and database.

$db['default'] = array(

    'dsn'    => '',

    'hostname' => 'localhost',

    'username' => 'root',

    'password' => '',

    'database' => 'sample',

    '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

);

4. autoload.php: Modify autoload.php file located at application-> config-> autoload.php.

$autoload['libraries'] = array('database');

$autoload['helper'] = array('url');

5. routes.php: It is located at application->config->routes.php. This file is used to call our default controller. 

$route['default_controller'] = ‘crudController’;

6. Index page: When your run it always call index() function available in controller. So set your landing page in index() function.

public function index()

{

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

}

Create Controller

First we have to create a controller in application-> controllers folder. I have created crudController.php.

As I said above controller contains all logics (ie. If..else.. for() loops, loading views etc…) of your project, I have created four functions for insert, update, delete and select respectively AddData(), UpdateData(), DeleteData() and DisplayData().

crudController.php       

<?php

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

    class crudController extends CI_Controller

    {

        function __construct()

        {

            parent::__construct();

            $this->load->helper('url'); /* Load base url */

            $this->load->model('crudModel'); /* Load model default which you create */

        }

        

        /* Set index page - First page */

        public function index()

        {

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

        }

        

        /* Function for display data */

        public function DisplayData()

        {

            $data["fetch_userdata"] = $this->crudModel->fetchuserdata();

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

        }

        

        /* Function for insert data */

        public function AddData()

        {

            if ($this->input->post("btnadd"))

            {

                $file = $_FILES["userprofile"]['name'];

                

                $config['upload_path']   = './assets/images';

                $config['allowed_types'] = 'jpg|jpeg|png|gif';

                

                $this->load->library('upload', $config);

                

                if (!$this->upload->do_upload('userprofile'))

                {

                    echo "<script>alert('Only select jpg,jpeg,png and gif images')</script>";

                }

                else

                {

                    $image     = $this->upload->data();

                    $checkbox1 = $this->input->post('hobby');

                    $chk       = "";

                    foreach ($checkbox1 as $chk1)

                    {

                        if ($chk == "")

                        {

                            $chk .= $chk1;

                        }

                        else

                        {

                            $chk .= "," . $chk1;

                        }

                    }

                    $data    = array(

                        'UserName' => $this->input->post('txtusername'),

                        'UserEmail' => $this->input->post('txtuseremail'),

                        'UserPassword' => $this->input->post('txtuserpass'),

                        'UserGender' => $this->input->post('rdogender'),

                        'UserHobbies' => $chk,

                        'UserProfile' => $image['file_name']

                    );

                    $success = $this->crudModel->adddata($data);

                    if ($success)

                    {

                        echo "<script>alert('Data added successfully..!!');window.location='http://localhost/CRUDOperationCI/index.php/crudController/DisplayData'</script>";

                    }

                    else

                    {

                        echo "<script>alert('Error while adding data..!!');window.location='http://localhost/CRUDOperationCI/'</script>";

                    }

                }

            }

        }

        

        /* Function for update data */

        public function UpdateData($id)

        {

            if ($this->input->post("btnupdate")) /* Update button click event */ 

            {

                $file = $_FILES['userprofile']['name'];

                

                $config['upload_path']   = './assets/images';

                $config['allowed_types'] = 'jpg|jpeg|png|gif';

                

                $this->load->library('upload', $config);

                $checkbox1 = $this->input->post('hobby');

                $chk       = "";

                foreach ($checkbox1 as $chk1)

                {

                    if ($chk == "")

                    {

                        $chk .= $chk1;

                    }

                    else

                    {

                        $chk .= "," . $chk1;

                    }

                }

                

                if ($this->upload->do_upload('userprofile'))

                {

                    $image   = $this->upload->data();

                    $data    = array(

                        'UserName' => $this->input->post('txtusername'),

                        'UserEmail' => $this->input->post('txtuseremail'),

                        'UserPassword' => $this->input->post('txtuserpass'),

                        'UserGender' => $this->input->post('rdogender'),

                        'UserHobbies' => $chk,

                        'UserProfile' => $image['file_name']

                    );

                    $success = $this->crudModel->updatedata($data, $id);

                    if ($success)

                    {

                        echo "<script>alert('Data updated successfully..!!');window.location='http://localhost/CRUDOperationCI/index.php/crudController/DisplayData'</script>";

                    }

                    else

                    {

                        echo "<script>alert('Error while updating data..!!');window.location='http://localhost/CRUDOperationCI/index.php/crudController/DisplayData'</script>";

                    }

                }

                else

                {

                    $data    = array(

                        'UserName' => $this->input->post('txtusername'),

                        'UserEmail' => $this->input->post('txtuseremail'),

                        'UserPassword' => $this->input->post('txtuserpass'),

                        'UserGender' => $this->input->post('rdogender'),

                        'UserHobbies' => $chk

                    );

                    $success = $this->crudModel->updatedata($data, $id);

                    if ($success)

                    {

                        echo "<script>alert('Data updated successfully..!!');window.location='http://localhost/CRUDOperationCI/index.php/crudController/DisplayData'</script>";

                    }

                    else

                    {

                        echo "<script>alert('Error while updating data..!!');window.location='http://localhost/CRUDOperationCI/index.php/crudController/DisplayData'</script>";

                    }

                }

            }

            if ($this->input->post("btncancel")) /* Cancel button click event */ 

            {

                echo "<script>window.location='http://localhost/CRUDOperationCI/index.php/crudController/DisplayData'</script>";

            }

            /* This two lines fetch a sinle record on which user has click to edit */

            $data["fetch_useriddata"] = $this->crudModel->fetcheditiddata($id);

            $this->load->view("updatemain", $data);

        }

        

        /* Function for delete data */

        public function DeleteData($id)

        {

            $success = $this->crudModel->deletedata($id);

            if ($success)

            {

                echo "<script>alert('Data deleted successfully..!!');window.location='http://localhost/CRUDOperationCI/index.php/crudController/DisplayData'</script>";

            }

            else

            {

                echo "<script>alert('Error while deleting data..!!');window.location='http://localhost/CRUDOperationCI/index.php/crudController/DisplayData'</script>";

            }

        }

    }

?>

Create Model

Now create a model in application->models folder. I created crudModel.php. As model contains all queries, I have created function to perform insert, update, delete and select queries respectively in adddata(), updatedata(), deletedata() and fetchuserdata(). Also one addition function fetcheditiddata() available to retrieve only single record when user click on edit.

crudModel.php

<?php

    class crudModel extends CI_Model

    {

        /* Insert query */

        function adddata($data)

        {

            $this->db->insert("tbluser", $data);

            return true;

        }

        

        /* Select query */

        function fetchuserdata()

        {

            $this->db->select('*');

            $this->db->from('tbluser');

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

            return $query->result();

        }

        

        /* Fetch data id wise for update */

        public function fetcheditiddata($id)

        {

            $this->db->select('*');

            $this->db->from('tbluser');

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

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

            return $query->row();

            

        }

        /* Update query */

        public function updatedata($data, $id)

        {

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

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

            return true;

        }

        

        /* Delete query */

        public function deletedata($id)

        {

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

            $this->db->delete('tbluser');

            return true;

        }

    }

?>

Create Views

Now create all views according to our requirements which will display to user in browser. It should be located into application->views folder. I have created main.php, display.php and updatemain.php files.

The main.php file used for adding data, display.php file used for view data and delete data, updatemain.php file used for edit data.

main.php

<!DOCTYPE html>

<html>

    <head>

        <title>Demo Codeigniter</title>

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

        <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

        <style>

        input[type=text],input[type=email],input[type=password]{

            width:100% !important;

        }

        table{

            border: 1px solid rgb(202,207,210);

        }

        form {

            margin: 10% auto 0;

        }

    </style>

    </head>

<body>

    <form method="post" enctype="multipart/form-data" action="<?php echo base_url();?>index.php/crudController/AddData">

    <center><h1>Registration Form CI</h1></center>

        <table border="0" align="center">

            <tr>

                <td>UserName:</td>

                <td><input type="text" name="txtusername" class="form-control"></td> 

            </tr>

            <tr>

                <td>UserEmail:</td>

                <td><input type="email" name="txtuseremail" class="form-control"></td>

            </tr>

            <tr>

                <td>UserPassword:</td>

                <td><input type="password" name="txtuserpass" class="form-control"></td>

            </tr>

            <tr>

                <td>Gender:</td>

                <td><input type="radio" name="rdogender" value="Male">Male <input type="radio" name="rdogender" value="Female">Female</td>

            </tr>

            <tr>

                <td>Hobbies:</td>

                <td><input type="checkbox" name="hobby[]" value="Cricket">Cricket <input type="checkbox" name="hobby[]" value="Hocky">Hocky</td>

            </tr>

            <tr>

                <td>UserProfile:</td>

                <td><input type="file" name="userprofile" class="form-control"> <span class="text-danger"></span></td>

            </tr>

            <tr>

                <td colspan="2" align="center"><input type="submit" name="btnadd" value="Add" class="btn btn-info"></td>

            </tr>

        </table>

    </form>

</body>

</html>

Note: In this file in form tag you must have to set action property. In action property set path of the function which you want to call while this form processed. Functions are written into controller.

action="<?php echo base_url(); ?>index.php/crudController/AddData"

where crudController in my controller name and AddData is my function name for inserting data.

display.php

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Display Data</title>

    <style>

        body{

            margin: 10% auto 0;

        }

        td{

            text-align: center;

        }

    </style>

</head>

<body>

    <center><h1>Display Data of User</h1></center>

    <table align="center" border="1">

        <tr>

            <th>Full Name</th>

            <th>Email Address</th>

            <th>Gender</th>

            <th>Hobbies</th>

            <th>Profile Picture</th>

            <th>Action</th>

        </tr>

   <?php

    foreach ($fetch_userdata as $row)

    {

   ?>

       <tr>

            <td><?php echo $row->UserName; ?></td>

            <td><?php echo $row->UserEmail; ?></td>

            <td><?php echo $row->UserGender; ?></td>

            <td><?php echo $row->UserHobbies; ?></td>

            <td><img src="<?php echo base_url(); ?>assets/images/<?php echo $row->UserProfile; ?>" height="100" width="100"/></td>

            <td><a href="<?php echo base_url(); ?>index.php/crudController/UpdateData/<?php echo $row->UserId; ?>">Edit</a> | <a href="<?php echo base_url(); ?>index.php/crudController/DeleteData/<?php echo $row->UserId; ?>">Delete</a></td>

        </tr>

   <?php

    }

   ?>

   </table>

</body>

</html>

updatemain.php

<!DOCTYPE html>

<html>

    <head>

        <title>Demo Codeigniter</title>

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

        <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

        <style>

        input[type=text],input[type=email],input[type=password]{

            width:100% !important;

        }

        table{

            border: 1px solid #CACFD2;

        }

        form {

            margin: 10% auto 0;

        }

    </style>

    </head>

<body>

    <form method="post" enctype="multipart/form-data">

    <center><h1>Edit Form CI</h1></center>

        <table border="0" align="center">

            <tr>

                <td>UserName:</td>

                <td><input type="text" name="txtusername" value="<?php echo $fetch_useriddata->UserName; ?>" class="form-control"></td> 

            </tr>

            <tr>

                <td>UserEmail:</td>

                <td><input type="email" name="txtuseremail" value="<?php echo $fetch_useriddata->UserEmail; ?>" class="form-control"></td>

            </tr>

            <tr>

                <td>UserPassword:</td>

                <td><input type="password" name="txtuserpass" value="<?php echo $fetch_useriddata->UserPassword; ?>" class="form-control"></td>

            </tr>

            <tr>

                <td>UserGender:</td>

                <td>

                 <?php

        if ($fetch_useriddata->UserGender == "Male")

        {

?>

                    <input type="radio" name="rdogender" value="Male" checked="true">Male <input type="radio" name="rdogender" value="Female">Female

                 <?php

        }

        else if ($fetch_useriddata->UserGender == "Female")

        {

?>

                    <input type="radio" name="rdogender" value="Male">Male <input type="radio" name="rdogender" value="Female" checked="true">Female

                 <?php

        }

?>

               </td> 

            </tr>

            <tr>

                <td>Hobbies:</td>

                <?php

        $ch1 = $ch2 = "";

        $myArray = explode(',', $fetch_useriddata->UserHobbies);

        foreach ($myArray as $chk)

        {

        if ($chk == "Cricket")

        {

                $ch1 = 'checked';

        }

        if ($chk == "Hocky")

        {

                $ch2 = 'checked';

        }

        }

?>

               <td><input type="checkbox" name="hobby[]" value="Cricket" <?php if ($ch1 == 'checked') echo "checked='checked'"; ?>>Cricket 

                   <input type="checkbox" name="hobby[]" value="Hocky" <?php if ($ch2 == 'checked') echo "checked='checked'"; ?>>Hocky</td>

            </tr>

            <tr>

                <td>UserProfile:</td>

                <td><input type="file" name="userprofile" class="form-control"> <img src="<?php echo base_url(); ?>assets/images/<?php echo $fetch_useriddata->UserProfile; ?>" width="100px" height="100px" alt=""></td>

            </tr>

            <tr>

                <td colspan="2" align="center"><input type="submit" name="btnupdate" value="Update" class="btn btn-info"> <input type="submit" name="btncancel" value="Cancel" class="btn btn-info"></td>

            </tr>

        </table>

    </form>

</body>

</html>

When you modify data and click on update button, it will redirect you to diplay.php page with updated record and Cancel button will redirect to display.php page without doing anything.

Click delete link to delete a record. There is no separate page for delete operation. It will simply call DeleteData() function of crudController.php and rest will be done by this function.

<a href="<?php echo base_url(); ?>index.php/crudController/DeleteData/<?php echo $row->UserId; ?>">Delete</a>

Hope you like the blog. If you have any query, please comment below..!!