PHP CODE IGNITER TUTORIAL

How To Crud Operation Using PHP Codeigniter

Written by admin

This tutorial will help to make an easy CRUD (Create Read Update Delete) operation application using MySQL database with validation. As we are cognizant that we always got to create basic CRUD modules for products, objects, etc. using MySQL database. this is often the first requirement for any web application. So during this example, I will be able to explain the instance of adding, editing, and deleting records using Codeigniter 3 and MySQL database. I’m extending this tutorial and can add functionality to insert update delete records from the MySQL database with the demo.

Here I explain step by step process to make, add, edit and delete records using Codeigniter 3.. you would like to follow some simple steps to make a basic CRUD application during a Kodinitor application.

1-Table structure for table tblusers
CREATE TABLE `add_student` (
  `id` int(11) NOT NULL,
  `name` varchar(45) DEFAULT NULL,
  `email` varchar(45) DEFAULT NULL,
  `phone` varchar(45) DEFAULT NULL,
  `gender` varchar(45) DEFAULT NULL,
  `country` varchar(45) DEFAULT NULL,
  `city` varchar(45) DEFAULT NULL,
  `qualification` varchar(45) DEFAULT NULL,
  `create_date` timestamp NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
2-Database configuration
application/config/database.php
$active_group = 'default';
$query_builder = TRUE;

$db['default'] = array(
	'dsn'	=> '',
	'hostname' => 'localhost',
	'username' => 'root',
	'password' => '',
	'database' => 'student_record',
	'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
);
3-Add to Libraries and helper
application/config/autoload.php
$autoload['libraries'] = array('database','session','form_validation');
$autoload['helper'] = array('html','url','form');
4-Create a view data(fetchdata.php)
application/views/fetchdata.php
<!DOCTYPE html>
<html lang="en">
<head>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

</head>
<body>

<div class="container">
  <h2>Display Data From Database </h2>
    <h3><a href="<?php echo site_url('Userdata/insertdata');?>">Add Record</a></h3>     
  <table class="table table-bordered">
     <p style="color: green;"><?php  echo $this->session->flashdata('success');?></p> 
              <p style="color:red"><?php  echo $this->session->flashdata('error');?></p>
    <thead>
                    <tr>
                      <th>#</th>
                      <th>Name</th>
                      <th>Email</th>
                      <th>Phone</th>
                      <th>Gender</th>
                      <th>Country</th>
                      <th>City</th>
                      <th>Qualification</th>
                      <th>Action</th>
                     </tr>
                  </thead>
                 <tbody>
<?php
if(count($result)) {
$cnt=1;
foreach ($result as $row){
?>

<tr>
<td><?php echo htmlentities($cnt);?></td>
<td hidden=""><?php echo htmlentities($row->id)?></td>
<td><?php echo htmlentities($row->name)?></td>
<td><?php echo htmlentities($row->email)?></td>
<td><?php echo htmlentities($row->phone)?></td>
<td><?php echo htmlentities($row->gender)?></td>
<td><?php echo htmlentities($row->country)?></td>
<td><?php echo htmlentities($row->city)?></td>
<td><?php echo htmlentities($row->qualification)?></td>
<td>
  <?php echo  anchor("Userdata/Edit/{$row->id}",' ','class="btn btn-primary btn-xs glyphicon glyphicon-pencil"')?>
<?php echo anchor("Userdata/delete/{$row->id}",' ','class="glyphicon glyphicon-trash btn-danger btn-xs"')?>
</td>

</tr>
<?php
$cnt++;
} // end foreach
} else { ?>
<tr>
<td colspan="7">No Record found</td>
</tr>
<?php
}
?>
</tbody>
  </table>
</div>

</body>
</html>
5-By default controller set(Userdata)
application/config/routes.php
$route['default_controller'] = 'Userdata';

6-Create a Controller(Userdata.php)
application/controllers/Userdata.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Userdata extends CI_Controller {


	public function index()
	{
	$this->load->model('Addnewrecord');
     $results=$this->Addnewrecord->fetchrecord();
     $this->load->view('fetchdata',['result'=>$results]);
	}

	public function insertdata()
	{
		
        $this->form_validation->set_rules('name','Name','required');
		$this->form_validation->set_rules('email','Email','required');
		$this->form_validation->set_rules('phone','Phone','required');
		$this->form_validation->set_rules('gender','Gender','required');
		$this->form_validation->set_rules('country','Country','required');
		$this->form_validation->set_rules('city','City','required');
		$this->form_validation->set_rules('qualification','Qualification','required');
		if($this->form_validation->run())
		{
		$name=$this->input->post('name');
		$email=$this->input->post('email');
		$phone=$this->input->post('phone');
		$gender=$this->input->post('gender');
		$country=$this->input->post('country');
		$city=$this->input->post('city');
		$qualification=$this->input->post('qualification');
		$this->load->model('Addnewrecord');
		$this->Addnewrecord->add($name,$email,$phone,$gender,$country,$city,$qualification);
		}
		 else{
		$this->load->view('add_new_record');
		}
	}

	public function Edit($id)
	{
	$this->load->model('Addnewrecord');
     $results=$this->Addnewrecord->editdata($id);
    $this->load->view('update',['row'=>$results]);
	}

	public function update(){
   $this->form_validation->set_rules('name','Name','required');
		$this->form_validation->set_rules('email','Email','required');
		$this->form_validation->set_rules('phone','Phone','required');
	    $this->form_validation->set_rules('city','City','required');
		$this->form_validation->set_rules('qualification','Qualification','required');
		if($this->form_validation->run())
		{
		$id=$this->input->post('id');
		$name=$this->input->post('name');
		$email=$this->input->post('email');
		$phone=$this->input->post('phone');
		$gender=$this->input->post('gender');
		$country=$this->input->post('country');
		$city=$this->input->post('city');
		$qualification=$this->input->post('qualification');
		
		$this->load->model('Addnewrecord');
		$this->Addnewrecord->updaterecord($id,$name,$email,$phone,$gender,$country,$city,$qualification);
		}
		 else{
		$this->load->view('fetchdata');
		}

	}

	public function delete($id)
	{
	$this->load->model('Addnewrecord');
     $results=$this->Addnewrecord->deleterow($id);
     $this->load->view('fetchdata');
	}
}


7-Create a Model(Addnewrecord.php)
application/models/Addnewrecord.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Addnewrecord extends CI_Model{
public function add($name,$email,$phone,$gender,$country,$city,$qualification){
	$data=array(
'name'=>$name,
'email'=>$email,
'phone'=>$phone,
'gender'=>$gender,
'country'=>$country,
'city'=>$city,
'qualification'=>$qualification,
);
	$query=$this->db->insert('add_student',$data);
	if($query){
$this->session->set_flashdata('success','New Record successfully.');	
redirect('Userdata/insertdata');
} else {
$this->session->set_flashdata('error','New Record not successfully.');	
redirect('Userdata/insertdata');	
}
	
}

		public function fetchrecord()
		{
			$query=$this->db->select('id,name,email,phone,gender,country,city,qualification')
			->get('add_student');
			return $query->result();
		}
        

		public function editdata($id){
		$ret=$this->db->select('id,name,email,phone,gender,country,city,qualification')
		->where('id',$id)
		->get('add_student');
		return $ret->row();
		}


         public function updaterecord($id,$name,$email,$phone,$gender,$country,$city,$qualification)
         {
		$data=array(
		'id'=>$id,
		'name'=>$name,
		'email'=>$email,
		'phone'=>$phone,
		'gender'=>$gender,
		'country'=>$country,
		'city'=>$city,
		'qualification'=>$qualification,
       );
		         $sql_query=$this->db->where('id', $id)
                ->update('add_student', $data);

                 if($sql_query){
$this->session->set_flashdata('success', 'Record updated successful');
		redirect('Userdata');
	}
	else{
		$this->session->set_flashdata('error', 'Record not updated successful');
		redirect('Userdata');
	}
         }
      
        public function deleterow($id){
			$sql_query=$this->db->where('id', $id)
			->delete('add_student');
			if($sql_query){
				$this->session->set_flashdata('success', 'Record delete successfully');
				redirect('Userdata');
			}
			else{
				$this->session->set_flashdata('error', 'Record not delete successfully!!');
				redirect('Userdata');
			}
		}
} 

8-Create a add new record data(add_new_record.php)
application/views/add_new_record.php
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<div class="container">    
     <div id="signupbox" style=" margin-top:50px" class="mainbox col-md-6 col-md-offset-3 col-sm-8 col-sm-offset-2">
        <div class="panel panel-info">
            <div class="panel-heading">
                <div class="panel-title">Insert data in database</div>
              </div>  
            <div class="panel-body" >
              <p style="color: green;"><?php  echo $this->session->flashdata('success');?></p> 
              <p style="color:red"><?php  echo $this->session->flashdata('error');?></p>  
              <?php echo form_error('name','<div style="color:red">','<div>');?>
              <?php echo form_error('email','<div style="color:red">','<div>');?>
              <?php echo form_error('phone','<div style="color:red">','<div>');?>
              <?php echo form_error('gender','<div style="color:red">','<div>');?>
              <?php echo form_error('country','<div style="color:red">','<div>');?>
              <?php echo form_error('city','<div style="color:red">','<div>');?>
              <?php echo form_error('qualification','<div style="color:red">','<div>');?>
               <?php echo form_open('Userdata/insertdata')?>
                         <label for="name" class="control-label col-md-4 ">Name</label>
                            <div class="controls col-md-8 ">
                                <?php echo form_input(['name'=>'name','id'=>'name','class'=>'form-control','style'=>'margin-bottom:10px']);?> 

                            </div>

                            <label for="email" class="control-label col-md-4"> E-mail</label>
                            <div class="controls col-md-8 ">
                              <?php echo form_input(['name'=>'email','id'=>'email','class'=>'form-control','style'=>'margin-bottom:10px']);?>
                            </div>     
                       
                        
                            <label for="phone" class="control-label col-md-4">Phone</label>
                            <div class="controls col-md-8 "> 
                                <?php echo form_input(['name'=>'phone','id'=>'phone','class'=>'form-control','style'=>'margin-bottom:10px']);?>
                            </div>
                        
                          <label for="id_gender"  class="control-label col-md-4  requiredField"> Gender </label>
                            <div class="controls col-md-8 "  style="margin-bottom: 10px">
                                 <label class="radio-inline"> 
                                 
                                <?php echo form_radio(['name'=>'gender','id'=>'gender','value'=>'Male','style'=>'margin-bottom:10px;']);?>Male
                                </label>

                                 <label class="radio-inline"> 
                                  <?php echo form_radio(['name'=>'gender','id'=>'gender','value'=>'Female','style'=>'margin-bottom:10px;']);?>Female

                                </label>
                            </div>
                      
                            <label for="id_company" class="control-label col-md-4  requiredField">Country </label>
                            <div class="controls col-md-8 "> 
                              <?php $options =array(
                                ''=>'select',
                                'India'=>'India',
                                'USA'=>'USA',
                              );
                              ?>
                            
                             <?php echo form_dropdown('country',$options,set_value(''),'class="form-control"');?>
                               
                           <br>
                            </div>
                       
                            <label for="id_company" class="control-label col-md-4  requiredField">City </label>
                            <div class="controls col-md-8 "> 
                              <?php echo form_input(['name'=>'city','id'=>'city','class'=>'form-control','style'=>'margin-bottom:10px']);?>
                            </div>
                         <label for="qualification" class="control-label col-md-4">Qualification</label>
                            <div class="controls col-md-8 "> 
                                <?php echo form_input(['name'=>'qualification','id'=>'qualification','class'=>'form-control','style'=>'margin-bottom:10px']);?>
                            </div>
                       <div class="form-group"> 
                            <div class="aab controls col-md-4 "></div>
                            <div class="controls col-md-8 ">
                               
                                <?php echo form_submit(['name'=>'submit','id'=>'submit','class'=>'btn btn-primary btn btn-info','value'=>'Submit'])?>
                                <a href="<?php echo site_url('userdata');?>">Back</a>
                              
                            </div>
                        </div> 
                  <?php echo form_close();?>
            </div>
        </div>
    </div> 
</div>
</div>            
9-Create a update data(update.php)
application/views/userform.php
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<div class="container">    
     <div id="signupbox" style=" margin-top:50px" class="mainbox col-md-6 col-md-offset-3 col-sm-8 col-sm-offset-2">
        <div class="panel panel-info">
            <div class="panel-heading">
                <div class="panel-title">Sign Up</div>
              </div>  
            <div class="panel-body" >
              <p style="color: green;"><?php  echo $this->session->flashdata('success');?></p> 
              <p style="color:red"><?php  echo $this->session->flashdata('error');?></p>  
             
               <?php echo form_open('Userdata/update')?>
                         <label for="name" class="control-label col-md-4 ">Name</label>
                            <div class="controls col-md-8 ">
                                <?php echo form_input(['name'=>'name','id'=>'name','class'=>'form-control','style'=>'margin-bottom:10px','value'=>set_value('name',$row->name)]);?>
                                  <?php echo form_hidden('id',$row->id);?>
                            </div>

                            <label for="email" class="control-label col-md-4"> E-mail</label>
                            <div class="controls col-md-8 ">
                              <?php echo form_input(['name'=>'email','id'=>'email','class'=>'form-control','style'=>'margin-bottom:10px','value'=>set_value('email',$row->email)]);?>
                            </div>     
                       
                        
                            <label for="phone" class="control-label col-md-4">Phone</label>
                            <div class="controls col-md-8 "> 
                                <?php echo form_input(['name'=>'phone','id'=>'phone','class'=>'form-control','style'=>'margin-bottom:10px','value'=>set_value('phone',$row->phone)]);?>
                            </div>
                        
                          <label for="id_gender"  class="control-label col-md-4  requiredField"> Gender </label>
                            <div class="controls col-md-8 "  style="margin-bottom: 10px">
                                 <label class="radio-inline"> 
                                 
                                <?php echo form_radio(['name'=>'gender','id'=>'gender','value'=>'Male','style'=>'margin-bottom:10px;','value'=>set_value('gender',$row->gender)]);?>Male
                                </label>

                                 <label class="radio-inline"> 
                                  <?php echo form_radio(['name'=>'gender','id'=>'gender','value'=>'Female','style'=>'margin-bottom:10px;','value'=>set_value('gender',$row->gender)]);?>Female

                                </label>
                            </div>
                      
                            <label for="id_company" class="control-label col-md-4  requiredField">Country </label>
                            <div class="controls col-md-8 "> 
                              <?php $options =array(
                                ''=>'select',
                                'India'=>'India',
                                'USA'=>'USA',
                              );
                              ?>
                            
                             <?php echo form_dropdown('country',$options,set_value(''),'class="form-control"');?>
                               
                           <br>
                            </div>
                       
                            <label for="id_company" class="control-label col-md-4  requiredField">City </label>
                            <div class="controls col-md-8 "> 
                              <?php echo form_input(['name'=>'city','id'=>'city','class'=>'form-control','style'=>'margin-bottom:10px','value'=>set_value('city',$row->city)]);?>
                            </div>
                         <label for="qualification" class="control-label col-md-4">Qualification</label>
                            <div class="controls col-md-8 "> 
                                <?php echo form_input(['name'=>'qualification','id'=>'qualification','class'=>'form-control','style'=>'margin-bottom:10px','value'=>set_value('qualification',$row->qualification)]);?>
                            </div>
                       <div class="form-group"> 
                            <div class="aab controls col-md-4 "></div>
                            <div class="controls col-md-8 ">
                               
                                <?php echo form_submit(['name'=>'submit','id'=>'submit','class'=>'btn btn-primary btn btn-info','value'=>'Update'])?>
                              
                            </div>
                        </div> 
                  <?php echo form_close();?>
            </div>
        </div>
    </div> 
</div>
</div>            
How To Crud Operation Using PHP Codeigniter with source code
Size: 2MB
Version: 3.11

About the author

admin

Hi there! I'm Shiv Gupta. I specialized in building Websites. I write blogs in my free time. I really like to find out and share my knowledge with others.I founded ThePhpConcept in March 2020. I started this blog in order that I can interact with some like-minded people and also help people learning PHP, Mysql, jQuery, Html, and PHP Projects and related technologies.
Support-thephpconcept@gmail.com

Leave a Comment

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