I have already covered login form and registration form in my previous posts. In this tutorial I am going to cover how to create CRUD in codeigniter. I am using previous example and code for this post. If you want to look my previous posts on codeigniter then visit below links.
- How to install Codeigniter in Xampp
- Codeigniter Framework Directory Structure
- How to create registration form in Codeigniter
- How to create login form in Codeigniter
I am going to explain create, read, update and delete data from the users table. This post is going to be bit long. Now let’s start.
Create CRUD in codeigniter:
Create Database:
1 2 3 4 |
Create database demo; Use demo; |
Create Users Table:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
CREATE TABLE `users` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `first_name` VARCHAR(255) NULL DEFAULT NULL, `last_name` VARCHAR(255) NULL DEFAULT NULL, `email` VARCHAR(255) NULL DEFAULT NULL, `phone` VARCHAR(255) NOT NULL, `password` VARCHAR(255) NULL DEFAULT NULL, `created` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ) COLLATE='latin1_swedish_ci' ENGINE=InnoDB AUTO_INCREMENT=8 |
Controllers:
First I will create controller file as Dashboard.php
. Remember Controller file must be start with capital letter and class name should match with controller file name.
Dashboard.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Dashboard extends CI_Controller { function __construct() { parent::__construct(); $this->load->model('user_model'); $this->load->library('form_validation'); } function index() { $data['getUsers'] = $this->user_model->getAllUsers(); $this->load->view('dashboard', $data); } function addUser() { //add user code will be here } function view() { //view user info code will be here } function editUser() { //edit user code will be here } function deleteUser() { //delete user code will be here } } |
In the construct function I have loaded the user model by calling $this->load->model('user_model')
and form validation library. I will discuss about user model later in this post. In index function I got all users in $data[‘getUsers’]
by calling getAllUsers()
function of user_model
. After that I loaded dashboard view and $data
array to the dashboard view. addUser()
, editUser()
and deleteUser()
will use later for CRUD.
Views:
Dashboard.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
<div class="container"> <div class="row"> <div class="col-md-12 text-center" style="margin:10px 0px "> <h2>Dashboard</h2> </div> <div class="col-md-12" style="margin:10px 0px "> <a class = "btn btn-primary" href="<?php echo base_url()."index.php/dashboard/addUser"?>">Add User</a> </div> <div class="col-md-12"> <?php if($this->session->flashdata('successMsg')) { echo '<div class="alert alert-success">'; echo $this->session->flashdata('successMsg'); echo '</div>'; } if($this->session->flashdata('errorMsg')) { echo '<div class="alert alert-info">'; echo $this->session->flashdata('errorMsg'); echo '</div>'; } if(!empty($getUsers)) { echo '<table class="table">'; echo '<tr>'; echo '<th>First Name</th>'; echo '<th>Last Name</th>'; echo '<th>Email</th>'; echo '<th>Action</th>'; echo '</tr>'; foreach($getUsers as $user) { echo '<tr>'; echo "<td>".$user['first_name']."</td>"; echo "<td>".$user['last_name']."</td>"; echo "<td>".$user['email']."</td>"; echo '<td><a href="'.base_url().'index.php/dashboard/view/'.$user["id"].'" class="btn btn-primary">View</a> <a class = "btn btn-primary" href="'.base_url().'index.php/dashboard/editUser/'.$user["id"].'">Edit</a> <a class = "btn btn-primary" href="'.base_url().'index.php/dashboard/deleteUser/'.$user["id"].'">Delete</a></td>'; echo '</tr>'; } echo '</table>'; } ?> </div> </div> </div> |
First of all I use not empty condition on $getUsers
array that we passed in controller. Then I print each row of $getUsers
by using foreach
loop. I have also created Add User, View, Edit, And Delete button to add, edit delete user respectively. After above writing above code my code will look like this.
Create Operation in Codeingiter CRUD:
Create Add User View:
Now I setup dashboard page successful now it’s time create add user code. First I will start with the view and create add user form in views/add_user.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
<div class="container"> <div class="row"> <div class="col-md-12 text-center"> <h2>Add User</h2> </div> <div class="col-md-5 col-md-offset-6 text-center"> <a class = "btn btn-primary" href="<?php echo base_url()."index.php/dashboard"?>">Back</a> </div </div> <div class="row"> <div class="col-md-12" style="margin:10px 0px "> <?php echo validation_errors(); if($this->session->flashdata('successMsg')) { echo '<div class="col-md-6 col-md-offset-3"><div class="alert alert-success">'; echo $this->session->flashdata('successMsg'); echo '</div></div>'; } if(isset($errorMsg)) { echo '<div class="col-md-6 col-md-offset-3"><div class="alert alert-danger">'; echo $errorMsg; echo '</div></div>'; unset($errorMsg); } ?> <form action="<?php echo base_url()."index.php/dashboard/addUser"?>" method="post"> <div class="form-group custom-bottom-margin"> <label class="control-label col-sm-4 text-right" for="name">First Name</label> <div class="col-sm-5"> <input type="text" name="first_name" class="form-control" value="<?php echo set_value('first_name'); ?>" placeholder="Enter First name" id="fname"> </div> </div> <div class="form-group custom-bottom-margin"> <label class="control-label col-sm-4 text-right" for="name">Last Name</label> <div class="col-sm-5"> <input type="text" name="last_name" class="form-control" value="<?php echo set_value('last_name'); ?>" placeholder="Enter Last name" id="lname"> </div> </div> <div class="form-group custom-bottom-margin"> <label class="control-label col-sm-4 text-right" for="email">Email</label> <div class="col-sm-5"> <input type="email" name="email" class="form-control" value="<?php echo set_value('email');?>" placeholder="Enter email" id="email"> </div> </div> <div class="form-group custom-bottom-margin"> <label class="control-label col-sm-4 text-right" for="password">Password</label> <div class="col-sm-5"> <input type="password" name="password" class="form-control" value="<?php echo set_value('password');?>" placeholder="Enter password" id="password"> </div> </div> <div class="form-group custom-bottom-margin"> <label class="control-label col-sm-4 text-right" for="phone">Phone</label> <div class="col-sm-5"> <input type="text" name="phone" class="form-control" value="<?php echo set_value('phone');?>" placeholder="Enter phone" id="phone"> </div> </div> <div class="form-group custom-bottom-margin"> <label class="control-label col-sm-4 text-right"></label> <div class="col-sm-5"> <button class="btn btn-primary" type="submit"> Submit</button> </div> </div> </form> </div> </div> </div> |
In the above code validation_errors()
is used to print validation errors and $this->session->flashdata('successMsg')
is used to print success message. $errorMsg
will also print error message if record will not save. After that there is add user form with 5 fields.
Create Add User Controller Function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
function addUser() { $this->form_validation->set_rules('first_name', 'First Name', 'trim|required'); $this->form_validation->set_rules('last_name', 'Last Name', 'trim|required'); $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email'); $this->form_validation->set_rules('password', 'Password', 'trim|required'); $this->form_validation->set_rules('phone', 'Phone', 'trim|required'); $this->form_validation->set_error_delimiters('<div class="col-md-6 col-md-offset-3"><div class="alert alert-danger">', '</div></div>'); if ($this->form_validation->run() == FALSE) { $this->load->view('add_user'); } else { $firstName = $this->security->xss_clean($this->input->post('first_name')); $lastName = $this->security->xss_clean($this->input->post('last_name')); $email = $this->security->xss_clean($this->input->post('email')); $password = $this->security->xss_clean($this->input->post('password')); $phone = $this->security->xss_clean($this->input->post('phone')); $options = array("cost"=>4); $hashPassword = password_hash($password,PASSWORD_BCRYPT,$options); $insertData = array('first_name'=>$firstName, 'last_name'=>$lastName, 'email'=>$email, 'phone'=>$phone, 'password'=>$hashPassword); $checkDuplicate = $this->user_model->checkDuplicate($email); if($checkDuplicate == 0) { $insertUser = $this->user_model->insertUser($insertData); if($insertUser) { $this->session->set_flashdata('successMsg', 'User has been added successfully'); redirect('dashboard/addUser'); } else { $data['errorMsg'] = 'Unable to save user. Please try again'; $this->load->view('add_user', $data); } } else { $data['errorMsg'] = 'User email alreary exists'; $this->load->view('add_user', $data); } } } |
Read Operation in Codeingiter CRUD:
Create Read View:
Create Operation is done in CRUD now I am creating Read operation. Now I am going to create read view file view-info.php
in views folder.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
<div class="container"> <div class="row"> <div class="col-md-12 text-center" style="margin:10px 0px "> <h2>View Info</h2> </div> <div class="col-md-12 text-right" style="margin:10px 0px"> <a class = "btn btn-primary" href="<?php echo base_url()."index.php/dashboard"?>">Back</a> </div> <div class="col-md-12"> <?php if(!empty($userInfo)) { echo '<table class="table">'; echo '<tr>'; echo '<th>First Name</th>'; echo '<th>Last Name</th>'; echo '<th>Email</th>'; echo '<th>Phone</th>'; echo '<th>Created</th>'; echo '</tr>'; echo '<tr>'; echo '<td>'.$userInfo["first_name"].'</td>'; echo '<td>'.$userInfo["last_name"].'</td>'; echo '<td>'.$userInfo["email"].'</td>'; echo '<td>'.$userInfo["phone"].'</td>'; echo '<td>'.$userInfo["created"].'</td>'; echo '</tr>'; echo '</table>'; } ?> </div> </div> </div> |
Create View Controller Function:
1 2 3 4 5 6 7 8 9 |
function view($id) { $getUserID = $id; $data['userInfo'] = $this->user_model->getUserByID($getUserID); $this->load->view('view-info', $data); } |
Update Operation in Codeingiter Crud:
Create Update View:
Read user operation is done now it’s time to create update operation. First I have to create edit user form and show respective data in input fields for editing.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
<div class="container"> <div class="row"> <div class="col-md-12 text-center"> <h2>Edit User</h2> </div> <div class="col-md-5 col-md-offset-6 text-center"> <a class = "btn btn-primary" href="<?php echo base_url()."index.php/dashboard"?>">Back</a> </div> </div> <div class="row"> <div class="col-md-12" style="margin:10px 0px "> <?php echo validation_errors(); if($this->session->flashdata('successMsg')) { echo '<div class="col-md-6 col-md-offset-3"><div class="alert alert-success">'; echo $this->session->flashdata('successMsg'); echo '</div></div>'; } if(isset($errorMsg)) { echo '<div class="col-md-6 col-md-offset-3"><div class="alert alert-danger">'; echo $errorMsg; echo '</div></div>'; unset($errorMsg); } ?> <form action="<?php echo base_url()."index.php/dashboard/editUser/".$userInfo['id']?>" method="post"> <div class="form-group custom-bottom-margin"> <label class="control-label col-sm-4 text-right" for="name">First Name</label> <div class="col-sm-5"> <input type="text" name="first_name" class="form-control" value="<?php echo $userInfo['first_name'] ?>" placeholder="Enter First name" id="fname"> </div> </div> <div class="form-group custom-bottom-margin"> <label class="control-label col-sm-4 text-right" for="name">Last Name</label> <div class="col-sm-5"> <input type="text" name="last_name" class="form-control" value="<?php echo $userInfo['last_name']; ?>" placeholder="Enter Last name" id="lname"> </div> </div> <div class="form-group custom-bottom-margin"> <label class="control-label col-sm-4 text-right" for="email">Email</label> <div class="col-sm-5"> <input type="email" name="email" class="form-control" value="<?php echo $userInfo['email'];?>" placeholder="Enter email" id="email"> </div> </div> <div class="form-group custom-bottom-margin"> <label class="control-label col-sm-4 text-right" for="password">Password</label> <div class="col-sm-5"> <input type="password" name="password" class="form-control" placeholder="Update password" id="password"> </div> </div> <div class="form-group custom-bottom-margin"> <label class="control-label col-sm-4 text-right" for="phone">Phone</label> <div class="col-sm-5"> <input type="text" name="phone" class="form-control" value="<?php echo $userInfo['phone'];?>" placeholder="Enter phone" id="phone"> </div> </div> <div class="form-group custom-bottom-margin"> <label class="control-label col-sm-4 text-right"></label> <div class="col-sm-5"> <button class="btn btn-primary" type="submit"> Submit</button> </div> </div> </form> </div> </div> </div> |
Create Update Controller Function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
function editUser($id) { $getUserID = $id; $data['userInfo'] = $this->user_model->getUserByID($getUserID); $this->form_validation->set_rules('first_name', 'First Name', 'trim|required'); $this->form_validation->set_rules('last_name', 'Last Name', 'trim|required'); $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email'); $this->form_validation->set_rules('password', 'Password', 'trim|required'); $this->form_validation->set_rules('phone', 'Phone', 'trim|required'); $this->form_validation->set_error_delimiters('<div class="col-md-6 col-md-offset-3"><div class="alert alert-danger">', '</div></div>'); if ($this->form_validation->run() == FALSE) { $this->load->view('edit_user',$data); } else { $firstName = $this->security->xss_clean($this->input->post('first_name')); $lastName = $this->security->xss_clean($this->input->post('last_name')); $email = $this->security->xss_clean($this->input->post('email')); $password = $this->security->xss_clean($this->input->post('password')); $phone = $this->security->xss_clean($this->input->post('phone')); $options = array("cost"=>4); $hashPassword = password_hash($password,PASSWORD_BCRYPT,$options); $updateData = array('first_name'=>$firstName, 'last_name'=>$lastName, 'email'=>$email, 'phone'=>$phone, 'password'=>$hashPassword); $update = $this->user_model->updateUser($updateData, $getUserID); if($update) { $this->session->set_flashdata('successMsg', 'User has been updated successfully'); redirect('dashboard/editUser/'.$getUserID); } else { $data['errorMsg'] = 'Unable to update user. Please try again'; $this->load->view('edit_user',$data); } } } |
Delete Operation in Codeingiter Crud:
So I have wrote Create, Read and Update operations in CRUD. Now it’s time to create last operation in CRUD that is Delete. I don’t need to create any view on delete operation. I just need to delete a record on clicking delete button in dashboard and show successful message if record would delete successfully.
Create Delete Controller Function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
function deleteUser($id) { if($this->user_model->deleteUser($id)) { $this->session->set_flashdata('successMsg', 'User has been updated successfully'); redirect('dashboard'); } else { $this->session->set_flashdata('errorMsg', 'Unable to delete user'); redirect('dashboard'); } } |
Models:
User_model.php
User_model.php file has necessary functions which will communicate to database.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 |
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class User_model extends CI_Model { function __construct() { parent::__construct(); } function checkDuplicate($email) { $this->db->select('email'); $this->db->from('users'); $this->db->like('email', $email); return $this->db->count_all_results(); } function insertUser($data) { if($this->db->insert('users', $data)) { return $this->db->insert_id(); } else { return false; } } function updateUser($data,$id) { if($this->db->update('users', $data, 'id = '.$id)) { return true; } else { return false; } } function deleteUser($id) { if($this->db->delete('users', array('id' => $id))) { return true; } else { return false; } } function userExist($email) { $this->db->select('*'); $this->db->like('email', $email); $qry = $this->db->get('users'); $rs = $qry->result_array(); return $rs[0]; } function getAllUsers() { $this->db->select('*'); $qry = $this->db->get('users'); $rs = $qry->result_array(); return $rs; } function getUserByID($id) { $this->db->select('*'); $this->db->like('id', $id); $qry = $this->db->get('users'); $rs = $qry->result_array(); return $rs[0]; } } |