CRUDL tasks on codeigniter

Complete tutorial on how to create simple CRUDL forms and action handlers on codeigniter.

In this simple tutorial we will be demonstrating the most useful tasks on any web applications. CRUDL (Create, Read, Update, Delete, List) are the common operations for any data-driven applications. This tutorial is very basic and simple intended for beginners on php codeigniter framework.

Lets create simple user management module.

Database table

Our first job is create database table to persist user information. Here is the script to create mysql database table to store users.

CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(100) NOT NULL DEFAULT '',
  `email` varchar(100) NOT NULL DEFAULT '',
  `password` varchar(200) NOT NULL DEFAULT '',
  `name` varchar(100) DEFAULT NULL,
  `role` varchar(50) DEFAULT NULL,
  `profileimage` varchar(200) DEFAULT NULL,
  `summary` varchar(500) DEFAULT NULL,
  PRIMARY KEY (`id`)
);

Next we create a CI controller class. It is responsible to insert,update,delete,load data.

class AdminUser extends CI_Controller{
   public function __construct()
 {
    parent::__construct();
 }
  ....
 }

Add a index method to load list of users from the database and pass it to the view which turn displays the users in tabular format.

public function index(){
       $this->load();
}
function load()
{
    $users=$this->db->get('users');
    $data['title']="List of Users";
    $data['desc']="User management";
    $data['sites']=$users;
    //load header view if here
    $this->load->view('admin/user/index',$data);
}

Here is the content of index.php view file under views/admin/user/ folder.

 <div class="container">
    <div class="row-fluid">

        <div class="span12">
            <h2><?php echo($title) ?></h2>

            <p><?php echo($desc)?> </p>

            <div>
                <div class="">
                    <a  href="/adminuser/add" class="btn"><i class="fa fa-plus"></i> <span>Add</span> </a>
                </div>
                <table cellpadding="0" cellspacing="0" id="users" class="table table-bordered">
                    <tr>
                        <th>Username</th>
                        <th>Email</th>
                        <th>Name</th>
                        <th>Edit</th>
                    </tr>

                    <?php foreach ($users->result() as $row): ?>
                        <tr id="row<?php echo($row->id) ?>">
                            <td>
                                <?php echo($row->username) ?>
                            </td>
                            <td>
                                <?php echo($row->email) ?>
                            </td>
                            <td>
                                <?php echo($row->name) ?>
                            </td>
                            <td>
                                <a class="edit btn btn-small" href="/adminuser/edit/<?php echo($row->id) ?>" ><i class="fa fa-edit"></i>
                                    Edit</a>

                            </td>
                        </tr>
                    <?php endforeach; ?>
                </table>
            </div>

        </div>
    </div>
</div> 

Now lets create a add function on the controller. It loads the new user form.

public function add()
{
    $userdata = $this->session->flashdata('userdata');
    $user = new ArrayObject();
    if ($userdata == null) {
        $user->name = '';
        $user->username = '';
        $user->email = '';
        $user->role = '';
    } else {
        $user->name = $userdata['name'];
        $user->username = $userdata['username'];
        $user->email = $userdata['email'];
        $user->role = $userdata['role'];
    }
    $data['title'] = "Add new User";
    $data['desc'] = "User management";
    $data['user'] = $user;
    // load header view here if you want to
    $this->load->view('admin/user/add', $data);
}

The view file add.php is simply a from that posts data to /adminuser/doadd method.

Here is the doadd method

public function doadd()
{
    $data = $this->getPostData(true);
    $success = false;
    $error = '';

    $success = $this->db->insert('users', $data);
    $id = $this->db->insert_id();
    if ($success) {
        $this->session->set_flashdata('message', 'New User added successfully!');
        redirect('/adminuser/edit/' . $id);
    } else {
        $this->session->set_flashdata('error', 'User cannot be added. Make sure username and email are available!<br/>' . $error);
        $this->session->set_flashdata('userdata', $data);
        redirect('/adminuser/add/');
    }
}

public function getPostData($withPassword)
{
    $username = $_POST['username'];
    $email = $_POST['email'];
    $name = $_POST['name'];
    $role = $_POST['role'];
    $password = $_POST['password'];
    $data = array('name' => $name, 'username' => $username, 'email' => $email, 'role' => $role);
    if ($withPassword || ($password != null && $password != '')) {
        $data['password'] = MD5($password);
    }
    return $data;
}

Next its time to create a edit form. The edit function loads user object from the database and loads the edit form along with selected user information.

public function edit()
{
    $id = $this->uri->segment(3);
    $this->db->where('id', $id);
    $blocks = $this->db->get('users');
    $bresult = $blocks->result();

    $user = $bresult[0];
    $data['title'] = "Edit User";
    $data['desc'] = "User management";
    $data['user'] = $user;

    $this->load->view('admin/header', $data);
    $this->load->view('admin/user/edit', $data);
}

The edit form simply has the same form elements that of add form. It posts changed data to update method which saves changes to the database and displays error or success message accordingly.

    public function update()
{

    $id = $this->uri->segment(3);
    $this->db->where('id', $id);

    $success = $this->db->update('users', $this->getPostData(false));
    if ($success) {
        $this->session->set_flashdata('message', 'User updated successfully!');
        redirect('/adminuser/edit/' . $id);
    } else {
        $this->session->set_flashdata('error', 'Error updating user. Please try again!');
        redirect('/adminuser/edit/' . $id);
    }
}

At last we create a delete handler on the controller. It tries to delete user from the database and if done successfully redirects to the user list page and displays the success message.

Here is the delete method:

public function delete()
 {
    $id = $this->uri->segment(3);
    $data = array('id' => $id);
    $success = $this->db->delete('users', $data);
    if ($success) {
        $this->session->set_flashdata('message', 'User deleted successfully!');
        redirect('/adminuser/index/');
    } else {
        $this->session->set_flashdata('error', 'Error deleting user. Please try again!');
        redirect('/adminuser/edit/' . $id);
    }
  }

Part of the view code for deleting user information.

<form class="form-inline" action="/adminuser/delete/<?php echo($user->id) ?>">
 <input type="submit" class="btn btn-primary" onclick="return confirm('Do you want to delete?');" value="Delete"/>

 </form>