Codeigniter

CRUD operation in CodeIgniter

In this tutorial we will learn aboout CRUD operation in CodeIgniter. CRUD Stands for create, read, update and delete record in the database.
SQL table tblusers structure used in this CRUD Operation.

CREATE TABLE `tblusers` (
  `id` int(11) NOT NULL,
  `FirstName` varchar(150) NOT NULL,
  `LastName` varchar(150) NOT NULL,
  `EmailId` varchar(120) NOT NULL,
  `ContactNumber` char(11) NOT NULL,
  `Address` varchar(255) NOT NULL,
  `PostingDate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `tblusers` ADD PRIMARY KEY (`id`);
ALTER TABLE `tblusers`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
COMMIT;

1.Create a database then configure your db credential in application/database.php

$active_group = 'default';
$query_builder = TRUE;
$db['default'] = array(
	'dsn'	=> '',
	'hostname' => 'localhost', // your hostname
	'username' => 'root', // your DB username
	'password' => '',     // DB password
	'database' => 'cicrud', // your database name
	'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
);

2. Load libraries and helpers in application/autoload.php that used in this CRUD operation.

$autoload['libraries'] = array('form_validation','session','database');
$autoload['helper'] = array('url','html','form');
  • Database library used for database related queries
  • Session library  used for display success / error message using flashdata.
  • form_validation library used for form validation rules.
  • Html Helper for used for link_tag
  • form helper used for form
  • url helper used for base_url.

For Data insertion (Create Operation)

Create a view for data insertion (insert.php) inside application/views

<div class="container">
<div class="row">
<div class="col-md-12">
<h3>Insert Record |  CRUD Operations using CodeIgniter</h3>
<hr />
</div>
</div>
<?php echo form_open('',['name'=>'insertdata','autocomplete'=>'off']);?>
<div class="row">
<div class="col-md-4"><b>First Name</b>
<?php echo form_input(['name'=>'firstname','class'=>'form-control','value'=>set_value('firstname')]);?>
<?php echo form_error('firstname',"<div style='color:red'>","</div>");?>
</div>
<div class="col-md-4"><b>Last Name</b>
<?php echo form_input(['name'=>'lastname','class'=>'form-control','value'=>set_value('lastname')]);?>
<?php echo form_error('lastname',"<div style='color:red'>","</div>");?>
</div>
</div>
<div class="row">
<div class="col-md-4"><b>Email id</b>
<?php echo form_input(['name'=>'emailid','class'=>'form-control','value'=>set_value('emailid')]);?>
<?php echo form_error('emailid',"<div style='color:red'>","</div>");?>
</div>
<div class="col-md-4"><b>Contactno</b>
<?php echo form_input(['name'=>'contactno','class'=>'form-control','value'=>set_value('contactno')]);?>
<?php echo form_error('contactno',"<div style='color:red'>","</div>");?>
</div>
</div>
<div class="row">
<div class="col-md-8"><b>Address</b>
<?php echo form_textarea(['name'=>'address','class'=>'form-control','value'=>set_value('address')]);?>
<?php echo form_error('address',"<div style='color:red'>","</div>");?>
</div>
</div>
<div class="row" style="margin-top:1%">
<div class="col-md-8">
<?php echo form_submit(['name'=>'insert','value'=>'Submit']);?>
</div>
</div>
<?php echo form_close();?>
</div>
</div>

Create a controller for data insertion (Insert.php) inside application/controller. Set the validation rules in this controller.

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Insert extends CI_Controller {
// For data insertion
public function index(){
//Setting validation rules
$this->form_validation->set_rules('firstname','First Name','required|alpha');
$this->form_validation->set_rules('lastname','Last Name','required|alpha');
$this->form_validation->set_rules('emailid','Email id','required|valid_email');
$this->form_validation->set_rules('contactno','Contact Number','required|numeric|exact_length[10]');
$this->form_validation->set_rules('address','Address','required');
if($this->form_validation->run()){
$fname=$this->input->post('firstname');
$lname=$this->input->post('lastname');
$email=$this->input->post('emailid');
$cntno=$this->input->post('contactno');
$adrss=$this->input->post('address');
//loading model
$this->load->model('Insert_Model');
$this->Insert_Model->insertdata($fname,$lname,$email,$cntno,$adrss);
$this->load->view('insert');
} else {
$this->load->view('insert');
}
}
}

Create a model (Insert_Model.php) inside application/model.

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Insert_Model extends CI_Model {
public function insertdata($fname,$lname,$email,$cntno,$adrss){
$data=array(
			'FirstName'=>$fname,
			'LastName'=>$lname,
			'EmailId'=>$email,
			'ContactNumber'=>$cntno,
			'Address'=>$adrss
		);
$sql_query=$this->db->insert('tblusers',$data);
if($sql_query){
$this->session->set_flashdata('success', 'Registration successful');
		redirect('read');
	}
	else{
		$this->session->set_flashdata('error', 'Somthing went worng. Error!!');
		redirect('read');
	}
	}}

For Data Fetching (Read Operation)

Create a model (Read_Model.php inside application/models) for reading data from database using Active Records .

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Read_Model extends CI_Model{
public function getdata(){
$query=$this->db->select('FirstName,LastName,EmailId,ContactNumber,Address,PostingDate,id')
		->get('tblusers');
		 return $query->result();
	}
}

Now create a controller (Read.php) inside application/controller.

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Read extends CI_Controller{
// for all records
public function index(){
//loading model
$this->load->model('Read_Model');
$results=$this->Read_Model->getdata();
// Passing values to view
$this->load->view('read',['result'=>$results]);
}
}

Create a view(read.php inside application/views) for showing data.

<div class="container">
<div class="row">
<div class="col-md-12">
<h3>CRUD Operations using CodeIgniter</h3> <hr />
<!--- Success Message --->
<?php if ($this->session->flashdata('success')) { ?>
<p style="font-size: 20px; color:green"><?php echo $this->session->flashdata('success'); ?></p>
<?php }?>
<!---- Error Message ---->
<?php if ($this->session->flashdata('error')) { ?>
<p style="font-size: 20px; color:red"><?php echo $this->session->flashdata('error'); ?></p>
 <?php } ?>
<a href="<?php echo site_url('insert'); ?>">
<button class="btn btn-primary"> Insert Record</button></a>
<div class="table-responsive">
<table id="mytable" class="table table-bordred table-striped">
<thead>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Contact</th>
<th>Address</th>
<th>Posting Date</th>
<th>Edit</th>
<th>Delete</th>
</thead>
<tbody>
<?php
$cnt=1;
foreach($result as $row)
{
?>
    <tr>
    <td><?php echo htmlentities($cnt);?></td>
    <td><?php echo htmlentities($row->FirstName);?></td>
    <td><?php echo htmlentities($row->LastName);?></td>
    <td><?php echo htmlentities($row->EmailId);?></td>
    <td><?php echo htmlentities($row->ContactNumber);?></td>
    <td><?php echo htmlentities($row->Address);?></td>
    <td><?php echo htmlentities($row->PostingDate);?></td>
    <td>
<?php
//for passing row id to controller
 echo  anchor("Read/getdetails/{$row->id}",' ','class="btn btn-primary btn-xs glyphicon glyphicon-pencil"')?>
</td>
<td>
<?php
//for passing row id to controller
 echo anchor("Delete/index/{$row->id}",' ','class="glyphicon glyphicon-trash btn-danger btn-xs"')?>
</td>
</tr>
<?php
// for serial number increment
$cnt++;
} ?>
</tbody>
</table>
</div>
</div>
</div>
</div>

For Data Updation (Update Operation)

In previous operation we fetched all data from database.  Now whenever user will click on the edit button row id passed to controller on the basis of that row id we will fetch and update the data.
First we will fetch the particular row data then update . We already created a controller Read.php now add a  function with parameter “getdetails($uid)”  in this controller for fetch particular record.

// for particular recod
public function getdetails($uid)
{
//loading model
$this->load->model('Read_Model');
$reslt=$this->Read_Model->getuserdetail($uid);
// Passing Values to update view
$this->load->view('update',['row'=>$reslt]);
}

Now we will add a new function “getuserdetail($uid)” in Read_Model.php for fetching particular row data.

public function getuserdetail($uid){
		$ret=$this->db->select('FirstName,LastName,EmailId,ContactNumber,Address,PostingDate,id')
		              ->where('id',$uid)
		              ->get('tblusers');
		        return $ret->row();
	}

Create a view for data updation(update.php) inside application/views.

<div class="container">
<div class="row">
<div class="col-md-12">
<h3>Update Record |  CRUD Operations using CodeIgniter</h3>
<hr />
</div>
</div>
<!--- Success Message --->
<?php if ($this->session->flashdata('success')) { ?>
<p style="font-size: 18px; color:green"><?php echo $this->session->flashdata('success'); ?></p>
<?php }?>
<!---- Error Message ---->
<?php if ($this->session->flashdata('error')) { ?>
<p style="font-size: 18px; color:red"><?php	echo $this->session->flashdata('error'); ?></p>
 <?php } ?>
<?php echo form_open('Insert/updatedetails',['name'=>'insertdata','autocomplete'=>'off']);?>
<?php echo form_hidden('userid',$row->id);?>
<div class="row">
<div class="col-md-4"><b>First Name</b>
<?php echo form_input(['name'=>'firstname','class'=>'form-control','value'=>set_value('firstname',$row->FirstName)]);?>
<?php echo form_error('firstname',"<div style='color:red'>","</div>");?>
</div>
<div class="col-md-4"><b>Last Name</b>
<?php echo form_input(['name'=>'lastname','class'=>'form-control','value'=>set_value('lastname',$row->LastName)]);?>
<?php echo form_error('lastname',"<div style='color:red'>","</div>");?>
</div>
</div>
<div class="row">
<div class="col-md-4"><b>Email id</b>
<?php echo form_input(['name'=>'emailid','class'=>'form-control','value'=>set_value('emailid',$row->EmailId)]);?>
<?php echo form_error('emailid',"<div style='color:red'>","</div>");?>
</div>
<div class="col-md-4"><b>Contactno</b>
<?php echo form_input(['name'=>'contactno','class'=>'form-control','value'=>set_value('contactno',$row->ContactNumber)]);?>
<?php echo form_error('contactno',"<div style='color:red'>","</div>");?>
</div>
</div>
<div class="row">
<div class="col-md-8"><b>Address</b>
<?php echo form_textarea(['name'=>'address','class'=>'form-control','value'=>set_value('address',$row->Address)]);?>
<?php echo form_error('address',"<div style='color:red'>","</div>");?>
</div>
</div>
<div class="row" style="margin-top:1%">
<div class="col-md-8">
<?php echo form_submit(['name'=>'insert','value'=>'Update']);?>
</div>
</div>
<?php echo form_close();?>
</div>
</div>

Now add a function “updatedetails” in Insert.php for data updation and set validation rules in this controller.

// For data updation
public function updatedetails(){
$this->form_validation->set_rules('firstname','First Name','required|alpha');
$this->form_validation->set_rules('lastname','Last Name','required|alpha');
$this->form_validation->set_rules('emailid','Email id','required|valid_email');
$this->form_validation->set_rules('contactno','Contact Number','required|numeric|exact_length[10]');
$this->form_validation->set_rules('address','Address','required');
if($this->form_validation->run()){
$fname=$this->input->post('firstname');
$lname=$this->input->post('lastname');
$email=$this->input->post('emailid');
$cntno=$this->input->post('contactno');
$adrss=$this->input->post('address');
$usid=$this->input->post('userid');
$this->load->model('Insert_Model');
$this->Insert_Model->updatedetails($fname,$lname,$email,$cntno,$adrss,$usid);
} else {
$this->session->set_flashdata('error', 'Somthing went worng. Try again with valid details !!');
		redirect('read');
}
}

After this add a new function “updatedetails” in Insert_Model.php for data updation.

public function updatedetails($fname,$lname,$email,$cntno,$adrss,$usid){
$data=array(
			'FirstName'=>$fname,
			'LastName'=>$lname,
			'EmailId'=>$email,
			'ContactNumber'=>$cntno,
			'Address'=>$adrss
		);
$sql_query=$this->db->where('id', $usid)
                ->update('tblusers', $data);
           if($sql_query){
$this->session->set_flashdata('success', 'Record updated successful');
		redirect('read');
	}
	else{
		$this->session->set_flashdata('error', 'Somthing went worng. Error!!');
		redirect('read');
	}

For Data Deletion (Delete Operation)

Create a controller (Delete.php) inside application/contollers.

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Delete extends CI_Controller{
public function index($uid)
{
$this->load->model('Delete_Model');
$this->Delete_Model->deleterow($uid);
$this->load->view('read');
}
}

Now create a model for data deletion(Delete_Model.php) inside application/model.

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Delete_Model extends CI_Model {
public function deleterow($uid){
$sql_query=$this->db->where('id', $uid)
                ->delete('tblusers');
           if($sql_query){
$this->session->set_flashdata('success', 'Record delete successfully');
		redirect('read');
	}
	else{
		$this->session->set_flashdata('error', 'Somthing went worng. Error!!');
		redirect('read');
	}
}
}

View Demo ——————————————————-

View Demo

How to run this script

  1. Download the zip file .
  2. Extract the zip and copy cicrud folder
  3. Paste in root directory(For xampp htdocs and for wamp www)
  4. Open your browser put http://localhost/phpmyadmin
  5. Create a database cicrud
  6. Import sql file cicrud.sql
  7. Run your script http://localhost/cicrud

CRUD Operation in CodeIgniter (Download full script)
Size: 4.46 MB
Version: V 1

Recommended Tutorials for you


Related posts

Validation rules to a config file in CodeIgniter

Anuj Kumar

Form Validation in CodeIgniter

Anuj Kumar

CodeIgniter Controllers

Anuj Kumar

CodeIgniter Interview Questions and Answers

Anuj Kumar

CodeIgniter Libraries

Anuj Kumar

How to fetch data in CodeIgniter

Anuj Kumar

How to create form in CodeIgniter

Anuj Kumar

Active Record in CodeIgniter

Anuj Kumar

Data Insertion in CodeIgniter

Anuj Kumar

Leave a Comment

* By using this form you agree with the storage and handling of your data by this website.

This site uses Akismet to reduce spam. Learn how your comment data is processed.