PHP Codeigniter Tutorial: CRUD Example App with Bootstrap 4 and MySQL Database

Today, We want to share with you codeigniter crud.In this post we will show you edit and update data in codeigniter, hear for Codeigniter 3 – Basic CRUD application with MySQL Example with Demo we will give you demo and example for implement.In this post, we will learn about update record in codeigniter with an example.

how to add edit delete in codeigniter?

Database and Configuration (members table:)

CREATE TABLE IF NOT EXISTS `members` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `member_bios` text COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=16 ;

application/config/database.php

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


$active_group = 'default';
$query_builder = TRUE;


$db['default'] = array(
	'dsn'	=> '',
	'hostname' => 'localhost',
	'username' => 'pakainfo_v1',
	'password' => '[email protected]',
	'database' => 'demo_example',
	'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
);

Create Routes

application/config/routes.php

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


$route['default_controller'] = 'welcome';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;


$route['memberInfo'] = "memberInfo/index";
$route['memberInfo/(:num)'] = "memberInfo/show/$1";
$route['memberInfoCreate']['post'] = "memberInfo/store";
$route['memberInfoEdit/(:any)'] = "memberInfo/edit/$1";
$route['memberInfoUpdate/(:any)']['put'] = "memberInfo/update/$1";
$route['memberInfoDelete/(:any)']['delete'] = "memberInfo/delete/$1";

Add MemberInfo Controller (application/controllers/MemberInfo.php)

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class MemberInfo extends CI_Controller {


   public $memberInfo;


   /**
    * Get All Data from this method.
    *
    * @return Response
   */
   public function __construct() {
      parent::__construct(); 


      $this->load->library('form_validation');
      $this->load->library('session');
      $this->load->model('MemberInfoModel');


      $this->memberInfo = new MemberInfoModel;
   }


   /**
    * Display Data this method.
    *
    * @return Response
   */
   public function index()
   {
       $data['data'] = $this->memberInfo->get_memberInfo();


       $this->load->view('theme/header');       
       $this->load->view('memberInfo/list',$data);
       $this->load->view('theme/footer');
   }


   /**
    * Show Details this method.
    *
    * @return Response
   */
   public function show($id)
   {
      $member = $this->memberInfo->find_member($id);


      $this->load->view('theme/header');
      $this->load->view('memberInfo/show',array('member'=>$member));
      $this->load->view('theme/footer');
   }


   /**
    * Create from display on this method.
    *
    * @return Response
   */
   public function create()
   {
      $this->load->view('theme/header');
      $this->load->view('memberInfo/create');
      $this->load->view('theme/footer');   
   }


   /**
    * Store Data from this method.
    *
    * @return Response
   */
   public function store()
   {
        $this->form_validation->set_rules('title', 'Title', 'required');
        $this->form_validation->set_rules('member_bios', 'Description', 'required');


        if ($this->form_validation->run() == FALSE){
            $this->session->set_flashdata('errors', validation_errors());
            redirect(base_url('memberInfo/create'));
        }else{
           $this->memberInfo->insert_member();
           redirect(base_url('memberInfo'));
        }
    }


   /**
    * Edit Data from this method.
    *
    * @return Response
   */
   public function edit($id)
   {
       $member = $this->memberInfo->find_member($id);


       $this->load->view('theme/header');
       $this->load->view('memberInfo/edit',array('member'=>$member));
       $this->load->view('theme/footer');
   }


   /**
    * Update Data from this method.
    *
    * @return Response
   */
   public function update($id)
   {
        $this->form_validation->set_rules('title', 'Title', 'required');
        $this->form_validation->set_rules('member_bios', 'Description', 'required');


        if ($this->form_validation->run() == FALSE){
            $this->session->set_flashdata('errors', validation_errors());
            redirect(base_url('memberInfo/edit/'.$id));
        }else{ 
          $this->memberInfo->update_member($id);
          redirect(base_url('memberInfo'));
        }
   }


   /**
    * Delete Data from this method.
    *
    * @return Response
   */
   public function delete($id)
   {
       $member = $this->memberInfo->delete_member($id);
       redirect(base_url('memberInfo'));
   }
}

application/models/MemberInfo.php

<?php


class MemberInfoModel extends CI_Model{


    public function get_memberInfo(){
        if(!empty($this->input->get("search"))){
          $this->db->like('title', $this->input->get("search"));
          $this->db->or_like('member_bios', $this->input->get("search")); 
        }
        $query = $this->db->get("members");
        return $query->result();
    }


    public function insert_member()
    {    
        $data = array(
            'title' => $this->input->post('title'),
            'member_bios' => $this->input->post('member_bios')
        );
        return $this->db->insert('members', $data);
    }


    public function update_member($id) 
    {
        $data=array(
            'title' => $this->input->post('title'),
            'member_bios'=> $this->input->post('member_bios')
        );
        if($id==0){
            return $this->db->insert('members',$data);
        }else{
            $this->db->where('id',$id);
            return $this->db->update('members',$data);
        }        
    }


    public function find_member($id)
    {
        return $this->db->get_where('members', array('id' => $id))->row();
    }


    public function delete_member($id)
    {
        return $this->db->delete('members', array('id' => $id));
    }
}
?>

application/views/theme/header.php

<!DOCTYPE html>
<html>
<head>
    <title>Basic Crud operation in Codeigniter 3 - www.pakainfo.com</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
</head>
<body>
<div class="container">

application/views/theme/footer.php

  </div>
 </body>
</html>

application/views/memberInfo/list.php

<div class="row">
    <div class="col-lg-12 margin-tb">
        <div class="pull-left">
            <h2>Codeigniter 3 CRUD Example from scratch</h2>
        </div>
        <div class="pull-right">
            <a class="btn btn-success" href="<?php echo base_url('memberInfo/create') ?>"> Create New Member</a>
        </div>
    </div>
</div>


<table class="table table-bordered">


  <thead>
      <tr>
          <th>Title</th>
          <th>Description</th>
          <th width="220px">Action</th>
      </tr>
  </thead>


  <tbody>
   <?php foreach ($data as $member) { ?>      
      <tr>
          <td><?php echo $member->title; ?></td>
          <td><?php echo $member->member_bios; ?></td>          
      <td>
        <form method="DELETE" action="<?php echo base_url('memberInfo/delete/'.$member->id);?>">
          <a class="btn btn-info" href="<?php echo base_url('memberInfo/'.$member->id) ?>"> show</a>
         <a class="btn btn-primary" href="<?php echo base_url('memberInfo/edit/'.$member->id) ?>"> Edit</a>
          <button type="submit" class="btn btn-danger"> Delete</button>
        </form>
      </td>     
      </tr>
      <?php } ?>
  </tbody>


</table>

application/views/memberInfo/create.php

<div class="row">
    <div class="col-lg-12 margin-tb">
        <div class="pull-left">
            <h2>Add New Member</h2>
        </div>
        <div class="pull-right">
            <a class="btn btn-primary" href="<?php echo base_url('memberInfo');?>"> Back</a>
        </div>
    </div>
</div>


<form method="post" action="<?php echo base_url('memberInfoCreate');?>">
    <?php


    if ($this->session->flashdata('errors')){
        echo '<div class="alert alert-danger">';
        echo $this->session->flashdata('errors');
        echo "</div>";
    }


    ?>


    <div class="row">
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Member Title:</strong>
                <input type="text" name="title" class="form-control">
            </div>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Member Description:</strong>
                <textarea name="member_bios" class="form-control"></textarea>
            </div>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-12 text-center">
                <button type="submit" class="btn btn-primary">Submit</button>
        </div>
    </div>


</form>

application/views/memberInfo/show.php

<div class="row">
    <div class="col-lg-12 margin-tb">
        <div class="pull-left">
            <h2> Show Member</h2>
        </div>
        <div class="pull-right">
            <a class="btn btn-primary" href="<?php echo base_url('memberInfo');?>"> Back</a>
        </div>
    </div>
</div>


<div class="row">
    <div class="col-xs-12 col-sm-12 col-md-12">
        <div class="form-group">
            <strong>Title:</strong>
            <?php echo $member->title; ?>
        </div>
    </div>
    <div class="col-xs-12 col-sm-12 col-md-12">
        <div class="form-group">
            <strong>Member Description:</strong>
            <?php echo $member->member_bios; ?>
        </div>
    </div>
</div>

application/views/memberInfo/edit.php

<div class="row">
    <div class="col-lg-12 margin-tb">
        <div class="pull-left">
            <h2>Edit Member</h2>
        </div>
        <div class="pull-right">
            <a class="btn btn-primary" href="<?php echo base_url('memberInfo');?>"> Back</a>
        </div>
    </div>
</div>


<form method="post" action="<?php echo base_url('memberInfo/update/'.$member->id);?>">
    <?php


    if ($this->session->flashdata('errors')){
        echo '<div class="alert alert-danger">';
        echo $this->session->flashdata('errors');
        echo "</div>";
    }


    ?>


    <div class="row">
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Title:</strong>
                <input type="text" name="title" class="form-control" value="<?php echo $member->title; ?>">
            </div>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Member Description:</strong>
                <textarea name="member_bios" class="form-control"><?php echo $member->member_bios; ?></textarea>
            </div>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-12 text-center">
                <button type="submit" class="btn btn-primary">Submit</button>
        </div>
    </div>


</form>

I hope you get an idea about Codeigniter 3 CRUD (Create,Read,Update,Delete) via Mysql.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Read Also:  Laravel 6 WhereNotIn Query Example

About Pakainfo

I am Jaydeep Gondaliya, a software engineer, the founder and the person running Pakainfo. I'm a full-stack developer, entrepreneur and owner of Pakainfo.com. I live in India and I love to write tutorials and tips that can help to other artisan, a Passionate Blogger, who love to share the informative content on PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Pakainfo →

Leave a Reply

Your email address will not be published. Required fields are marked *