CodeIgniter CRUD Example Tutorial From Scratch

CodeIgniter CRUD Example Tutorial From Scratch

Today, We want to share with you CodeIgniter CRUD Example Tutorial From Scratch.In this post we will show you CodeIgniter AJAX CRUD using Bootstrap Modal Edit or Update, hear for Codeigniter Ajax Crud using DataTables – Delete – Remove Mysql Data we will give you demo and example for implement.In this post, we will learn about How to Create CURD Operation in Codeigniter with AJAX and Bootstrap with an example.

CodeIgniter CRUD Example Tutorial From Scratch

There are the Following The simple About CodeIgniter CRUD Example Tutorial From Scratch Full Information With Example and source code.

As I will cover this Post with live Working example to develop CodeIgniter CRUD using Ajax,Bootstrap,Models and MySQL, so the some major files and Directory structures for this example is following below.

  • CodeIgniter Database and Table
  • CodeIgniter constructor
  • Create CodeIgniter Controller
  • Make CodeIgniter Model
  • CodeIgniter CRUD(Create, Read, Update and Delete)

Step 1 : Create database and Table

create CodeIgniter the database for simple project

This is where I will make a simple HTML form and PHP server side source code for our web application. To make the forms simply all souce code copy and write it into your any text editor Like Notepad++, then save file it as create a table members using this SQL code..

Table structure for table `members`

CREATE TABLE `members` (
  `member_id` int(11) NOT NULL,
  `member_name` int(11) NOT NULL,
  `member_title` varchar(50) NOT NULL,
  `member_fname` varchar(50) NOT NULL,
  `member_category` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Step 2 : Dump Data for Members

Fake data for table “members”

INSERT INTO `members` (`member_id`, `member_name`, `member_title`, `member_fname`, `member_category`) VALUES
(2, 7893, 'Gondaliya Jaydeep', 'Jaydeep', 'devloping'),
(3, 8934, 'Hardik patel', 'Ankit', 'devloping'),
(6, 8902, 'bhavna patadiya', 'Krunal', 'testing'),
(7, 2345, 'Mayur Dhameliya', 'shah manshi', 'Designer'),
(8, 8927, 'sejal Ramani', 'Hiren', 'Designer'),
(9, 6723, 'chirag dethariya', 'Sir Vishal Pandya', 'testing'),
(10, 7896, 'Ankit kalariya', 'Deepali ', 'devloping'),
(11, 8978, 'Krunal sisodiya', 'jalpa patadiya', 'Mobile devloping'),
(12, 8987, 'Dhaval dave', 'Sir Jd patel', 'Physics'),
(13, 7890, 'vivek bharat bhai sojitra', 'Vivek kalariya', 'devloping'),
(14, 1234, 'Chandni umasanakar joshi', 'chandni joshi', 'devloping');

Step 3 : Create a CodeIgniter constructor

Make CodeIgniter constructor __construct()

public function __construct()
	 	{
	 		parent::__construct();
			$this->load->helper('url');
	 		$this->load->model('member_model');
	 	}

CodeIgniter models

	public function index()
	{
 
		$data['members']=$this->member_model->get_all_members();
		$this->load->view('member_view',$data);
	}

Member_add() method

public function member_add()
		{
			$data = array(
					'member_name' => $this->input->post('member_name'),
					'member_title' => $this->input->post('member_title'),
					'member_fname' => $this->input->post('member_fname'),
					'member_category' => $this->input->post('member_category'),
				);
			$insert = $this->member_model->member_add($data);
			echo json_encode(array("status" => TRUE));
		}

Ajax_edit() method

public function ajax_edit($id)
		{
			$data = $this->member_model->get_by_id($id);



			echo json_encode($data);
		}

Member_update() method

public function member_update()
	{
		$data = array(
				'member_name' => $this->input->post('member_name'),
				'member_title' => $this->input->post('member_title'),
				'member_fname' => $this->input->post('member_fname'),
				'member_category' => $this->input->post('member_category'),
			);
		$this->member_model->member_update(array('member_id' => $this->input->post('member_id')), $data);
		echo json_encode(array("status" => TRUE));
	}

Member_delete method

public function member_delete($id)
	{
		$this->member_model->delete_by_id($id);
		echo json_encode(array("status" => TRUE));
	}

Step 4 : CodeIgniter Controller (CodeIgniter CRUD Example Tutorial)

Member controller for CodeIgniter CRUD Example Tutorial

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


	 public function __construct()
	 	{
	 		parent::__construct();
			$this->load->helper('url');
	 		$this->load->model('member_model');
	 	}


	public function index()
	{

		$data['members']=$this->member_model->get_all_members();
		$this->load->view('member_view',$data);
	}
	public function member_add()
		{
			$data = array(
					'member_name' => $this->input->post('member_name'),
					'member_title' => $this->input->post('member_title'),
					'member_fname' => $this->input->post('member_fname'),
					'member_category' => $this->input->post('member_category'),
				);
			$insert = $this->member_model->member_add($data);
			echo json_encode(array("status" => TRUE));
		}
		public function ajax_edit($id)
		{
			$data = $this->member_model->get_by_id($id);



			echo json_encode($data);
		}

		public function member_update()
	{
		$data = array(
				'member_name' => $this->input->post('member_name'),
				'member_title' => $this->input->post('member_title'),
				'member_fname' => $this->input->post('member_fname'),
				'member_category' => $this->input->post('member_category'),
			);
		$this->member_model->member_update(array('member_id' => $this->input->post('member_id')), $data);
		echo json_encode(array("status" => TRUE));
	}

	public function member_delete($id)
	{
		$this->member_model->delete_by_id($id);
		echo json_encode(array("status" => TRUE));
	}



}

get_all_members() function

public function get_all_members()
{
$this->db->from('members');
$query=$this->db->get();
return $query->result();
}

Retrive single a member record

	public function get_by_id($id)
	{
		$this->db->from($this->table);
		$this->db->where('member_id',$id);
		$query = $this->db->get();

		return $query->row();
	}

Insert a member_add($data) method

	public function member_add($data)
	{
		$this->db->insert($this->table, $data);
		return $this->db->insert_id();
	}

update member_update($where, $data)

	public function member_update($where, $data)
	{
		$this->db->update($this->table, $data, $where);
		return $this->db->affected_rows();
	}

delete_by_id($id) function

	public function delete_by_id($id)
	{
		$this->db->where('member_id', $id);
		$this->db->delete($this->table);
	}

Step 5 : CodeIgniter Member Model

complete Member Model source code for CodeIgniter CRUD Example Tutorial

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

class Member_model extends CI_Model
{

	var $table = 'members';


	public function __construct()
	{
		parent::__construct();
		$this->load->database();
	}


public function get_all_members()
{
$this->db->from('members');
$query=$this->db->get();
return $query->result();
}


	public function get_by_id($id)
	{
		$this->db->from($this->table);
		$this->db->where('member_id',$id);
		$query = $this->db->get();

		return $query->row();
	}

	public function member_add($data)
	{
		$this->db->insert($this->table, $data);
		return $this->db->insert_id();
	}

	public function member_update($where, $data)
	{
		$this->db->update($this->table, $data, $where);
		return $this->db->affected_rows();
	}

	public function delete_by_id($id)
	{
		$this->db->where('member_id', $id);
		$this->db->delete($this->table);
	}


}

Step 6 : Display List View For CodeIgniter CRUD Example Tutorial

Create a member_view.php

<!DOCTYPE html>
<html>
    <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>CodeIgniter CRUD Example Tutorial From Scratch</title>
    <link href="<?php echo base_url('assests/bootstrap/css/bootstrap.min.css')?>" rel="stylesheet">
    <link href="<?php echo base_url('assests/datatables/css/dataTables.bootstrap.css')?>" rel="stylesheet">
  </head>
  <body>


  <div class="container">
    <h1>CodeIgniter CRUD Example Tutorial From Scratch</h1>
</center>
    <h3>Member Store</h3>
    <br />
    <button class="btn btn-success" onclick="add_member()"><i class="glyphicon glyphicon-plus"></i> Add Member</button>
    <br />
    <br />
    <table id="table_id" class="table table-striped table-bordered" cellspacing="0" width="100%">
      <thead>
        <tr>
					<th>Member ID</th>
					<th>Member Name</th>
					<th>Member Title</th>
					<th>Member Fname</th>
					<th>Member Category</th>

          <th style="width:125px;">Action
          </p></th>
        </tr>
      </thead>
      <tbody>
				<?php foreach($members as $member){?>
				     <tr>
				         <td><?php echo $member->member_id;?></td>
				         <td><?php echo $member->member_name;?></td>
								 <td><?php echo $member->member_title;?></td>
								<td><?php echo $member->member_fname;?></td>
								<td><?php echo $member->member_category;?></td>
								<td>
									<button class="btn btn-warning" onclick="edit_member(<?php echo $member->member_id;?>)"><i class="glyphicon glyphicon-pencil"></i></button>
									<button class="btn btn-danger" onclick="delete_member(<?php echo $member->member_id;?>)"><i class="glyphicon glyphicon-remove"></i></button>


								</td>
				      </tr>
				     <?php }?>



      </tbody>

      <tfoot>
        <tr>
          <th>Member ID</th>
          <th>Member Name</th>
          <th>Member Title</th>
          <th>Member Fname</th>
          <th>Member Category</th>
          <th>Action</th>
        </tr>
      </tfoot>
    </table>

  </div>

  <script src="<?php echo base_url('assests/<a href="https://www.phpcodify.com/category/jquery/">jquery</a>/jquery-3.1.0.min.js')?>"></script>
  <script src="<?php echo base_url('assests/bootstrap/js/bootstrap.min.js')?>"></script>
  <script src="<?php echo base_url('assests/datatables/js/jquery.dataTables.min.js')?>"></script>
  <script src="<?php echo base_url('assests/datatables/js/dataTables.bootstrap.js')?>"></script>


  <script type="text/javascript">
  $(document).ready( function () {
      $('#table_id').DataTable();
  } );
    var save_method; //for save method string
    var table;


    function add_member()
    {
      save_method = 'add';
      $('#form')[0].reset();
      $('#memberFrm').modal('show');
    }

    function edit_member(id)
    {
      save_method = 'update';
      $('#form')[0].reset(); 

      $.ajax({
        url : "<?php echo site_url('index.php/member/ajax_edit/')?>/" + id,
        type: "GET",
        dataType: "JSON",
        success: function(data)
        {

            $('[name="member_id"]').val(data.member_id);
            $('[name="member_name"]').val(data.member_name);
            $('[name="member_title"]').val(data.member_title);
            $('[name="member_fname"]').val(data.member_fname);
            $('[name="member_category"]').val(data.member_category);


            $('#memberFrm').modal('show');
            $('.modal-title').text('Edit Member');

        },
        error: function (jqXHR, textStatus, errorThrown)
        {
            alert('Error get data from ajax');
        }
    });
    }



    function save()
    {
      var url;
      if(save_method == 'add')
      {
          url = "<?php echo site_url('index.php/member/member_add')?>";
      }
      else
      {
        url = "<?php echo site_url('index.php/member/member_update')?>";
      }

          $.ajax({
            url : url,
            type: "POST",
            data: $('#form').serialize(),
            dataType: "JSON",
            success: function(data)
            {
               $('#memberFrm').modal('hide');
              location.reload();
            },
            error: function (jqXHR, textStatus, errorThrown)
            {
                alert('Error adding / update data');
            }
        });
    }

    function delete_member(id)
    {
      if(confirm('Are you sure delete this data?'))
      {
          $.ajax({
            url : "<?php echo site_url('index.php/member/member_delete')?>/"+id,
            type: "POST",
            dataType: "JSON",
            success: function(data)
            {
               
               location.reload();
            },
            error: function (jqXHR, textStatus, errorThrown)
            {
                alert('Error deleting data');
            }
        });

      }
    }

  </script>

  <div class="modal fade" id="memberFrm" role="dialog">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
        <h3 class="modal-title">Member Form</h3>
      </div>
      <div class="modal-body form">
        <form action="#" id="form" class="form-horizontal">
          <input type="hidden" value="" name="member_id"/>
          <div class="form-body">
            <div class="form-group">
              <label class="control-label col-md-3">Member Name</label>
              <div class="col-md-9">
                <input name="member_name" placeholder="Member Name" class="form-control" type="text">
              </div>
            </div>
            <div class="form-group">
              <label class="control-label col-md-3">Member Title</label>
              <div class="col-md-9">
                <input name="member_title" placeholder="Member_title" class="form-control" type="text">
              </div>
            </div>
            <div class="form-group">
              <label class="control-label col-md-3">Member Fname</label>
              <div class="col-md-9">
								<input name="member_fname" placeholder="Member Fname" class="form-control" type="text">

              </div>
            </div>
						<div class="form-group">
							<label class="control-label col-md-3">Member Category</label>
							<div class="col-md-9">
								<input name="member_category" placeholder="Member Category" class="form-control" type="text">

							</div>
						</div>

          </div>
        </form>
          </div>
          <div class="modal-footer">
            <button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
            <button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
          </div>
        </div>
      </div>
    </div>

  </body>
</html>

Angular 6 CRUD Operations Application Tutorials

Read :

  Laravel force https with url helper

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about CodeIgniter CRUD Example Tutorial From Scratch.
I would like to have feedback on my Pakainfo.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.

Leave a Reply

avatar
  Subscribe  
Notify of