Aplikasi CRUD Menggunakan CodeIgniter, dan Ajax

Kembali lagi dengan kami kali ini kami akan share bagaimana membuat aplikasi crud menggunakan CodeIgniter, datatables dan Aax, sebenarnya kami tidak akan menelaskan secara begitu detail karena filenya nanti bisa kalian download dibawah.



Kami hanya akan lebih bagaimana mengkonfigurasi aplikasi CRUD sederhana diatas, mulai dari mempersiapkan database, konfigurasi config file, configurasi database, koneksi kedatabse, dan tampilan form aplikasi di atas.

What Is CRUD ?

CRUD adalah singkatan dari Create, Retrieve, Update dan Delete untuk berinteraksi dengan data table database. Aplikasi Crud sangat sering digunakan sebagai pengetahuan atau pembelaaran untuk membuat suatu aplikasi.

Pada tahap pertama buka file config yaitu pada application / config / config.php kemudian harus mengubah basis URL agar bekerja dengan benar.
 $config['base_url'] = 'http://localhost:9080/cicrud'; 

Kedua buat struktur database, buat database dengan nama crudci kemudian anda masukkan struktur database dibawah ini.
 CREATE DATABASE `crudci`;
 
CREATE TABLE `crudci`.`members` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `fname` varchar(255) NOT NULL,
  `lname` varchar(255) NOT NULL,
  `age` varchar(255) NOT NULL,
  `contact` varchar(255) NOT NULL,
  `address` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; 

Berikutnya adalah membuta database terkoneksi dengan aplikasi caranya buka file databse pada application / config/ database.php kemudian masukkan nama database anda, lihat contoh dibawah.
 $db['default'] = array(
 'dsn' => '',
 'hostname' => 'localhost',
 'username' => 'root',
 'password' => '',
 'database' => 'crudci',
 '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
);
 

Buat file welcome.php pada folder controllers, file ini berfungsi sebagai controller yang digunakan mengatur alur aplikasi yang dibuat dalam hal ini meload file model member pada folder models.
 <?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Welcome extends CI_Controller {
 public function __construct() {
  parent::__construct();

  //form -validation
  $this->load->library('form_validation');

  $this->load->model('model_member');
 }

 public function index()
 {
  $this->load->view('home');
 }

 public function create() 
 {

  $validator = array('success' => false, 'messages' => array());

  $config = array(
     array(
        'field' => 'fname',
        'label' => 'First Name',
        'rules' => 'trim|required'
     ),
     array(
        'field' => 'age',
        'label' => 'Age',
        'rules' => 'trim|required|integer'             
     ),
     array(
        'field' => 'contact',
        'label' => 'Contact',
        'rules' => 'trim|required|integer'             
     )
  );

  $this->form_validation->set_rules($config);
  $this->form_validation->set_error_delimiters('<p class="text-danger">','</p>');

  if($this->form_validation->run() === true) {

   $createMember = $this->model_member->create(); 

   if($createMember === true) {
    $validator['success'] = true;
    $validator['messages'] = "Successfully added";
   } else {
    $validator['success'] = false;
    $validator['messages'] = "Error while updating the infromation";
   }   
  } 
  else {
   $validator['success'] = false;
   foreach ($_POST as $key => $value) {
    $validator['messages'][$key] = form_error($key); 
   }   
  }

  echo json_encode($validator);
 }

 public function fetchMemberData() 
 {
  $result = array('data' => array());

  $data = $this->model_member->fetchMemberData();
  foreach ($data as $key => $value) {
   $name = $value['fname'] . ' ' . $value['lname'];

   // button
   $buttons = '
   <div class="btn-group">
     <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
       Action <span class="caret"></span>
     </button>
     <ul class="dropdown-menu">
       <li><a type="button" onclick="editMember('.$value['id'].')" data-toggle="modal" data-target="#editMemberModal">Edit</a></li>
       <li><a type="button" onclick="removeMember('.$value['id'].')" data-toggle="modal" data-target="#removeMemberModal">Remove</a></li>       
     </ul>
   </div>
   ';

   $result['data'][$key] = array(
    $name,
    $value['age'],
    $value['contact'],
    $value['address'],
    $buttons
   );
  } // /foreach

  echo json_encode($result);
 }

 public function getSelectedMemberInfo($id) 
 {
  if($id) {
   $data = $this->model_member->fetchMemberData($id);
   echo json_encode($data);
  }
 }

 public function edit($id = null) 
 {
  if($id) {
   $validator = array('success' => false, 'messages' => array());

   $config = array(
      array(
         'field' => 'editFname',
         'label' => 'First Name',
         'rules' => 'trim|required'
      ),
      array(
         'field' => 'editAge',
         'label' => 'Age',
         'rules' => 'trim|required|integer'             
      ),
      array(
         'field' => 'editContact',
         'label' => 'Contact',
         'rules' => 'trim|required|integer'             
      )
   );

   $this->form_validation->set_rules($config);
   $this->form_validation->set_error_delimiters('<p class="text-danger">','</p>');

   if($this->form_validation->run() === true) {

    $editMember = $this->model_member->edit($id); 

    if($editMember === true) {
     $validator['success'] = true;
     $validator['messages'] = "Successfully updated";
    } else {
     $validator['success'] = false;
     $validator['messages'] = "Error while updating the infromation";
    }   
   } 
   else {
    $validator['success'] = false;
    foreach ($_POST as $key => $value) {
     $validator['messages'][$key] = form_error($key); 
    }   
   }

   echo json_encode($validator);
  }
 }

 public function remove($id = null)
 {
  if($id) {
   $validator = array('success' => false, 'messages' => array());

   $removeMember = $this->model_member->remove($id);
   if($removeMember === true) {
    $validator['success'] = true;
    $validator['messages'] = "Successfully removed";
   }
   else {
    $validator['success'] = true;
    $validator['messages'] = "Successfully removed";
   }

   echo json_encode($validator);
  }
 }


}
 

Berikutnya buat file model_member.php file berisi bait program yang digunakan untuk pengelolaan data ke database.
 <?php 

/**
* 
*/
class Model_Member extends CI_Model
{
 public function create() 
 {
  $data = array(
   'fname' => $this->input->post('fname'),
   'lname' => $this->input->post('lname'),
   'age' => $this->input->post('age'),
   'contact' => $this->input->post('contact'),
   'address' => $this->input->post('address')
  );

  $sql = $this->db->insert('members', $data);

  if($sql === true) {
   return true; 
  } else {
   return false;
  }
 } // /create function

 public function edit($id = null) 
 {
  if($id) {
   $data = array(
    'fname' => $this->input->post('editFname'),
    'lname' => $this->input->post('editLname'),
    'age' => $this->input->post('editAge'),
    'contact' => $this->input->post('editContact'),
    'address' => $this->input->post('editAddress')
   );

   $this->db->where('id', $id);
   $sql = $this->db->update('members', $data);

   if($sql === true) {
    return true; 
   } else {
    return false;
   }
  }
   
 }

 public function fetchMemberData($id = null) 
 {
  if($id) {
   $sql = "SELECT * FROM members WHERE id = ?";
   $query = $this->db->query($sql, array($id));
   return $query->row_array();
  }

  $sql = "SELECT * FROM members";
  $query = $this->db->query($sql);
  return $query->result_array();
 }

 public function remove($id = null) {
  if($id) {
   $sql = "DELETE FROM members WHERE id = ?";
   $query = $this->db->query($sql, array($id));

   // ternary operator
   return ($query === true) ? true : false;   
  } // /if
 }
 
} 

Terakhir kita buat form atau tampilan dari aplikasi crud, buat file denga nama home.php dan simpan filenya pada folder views.
 <!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8">
 <title>Crud CodeIgniter</title>
 <!-- bootstrap -->
 <link rel="stylesheet" type="text/css" href="assets/bootstrap/css/bootstrap.min.css">
 <!-- datatables css -->
 <link type="text/css" href='https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css' rel='stylesheet'>
 <link type="text/css" href='https://cdn.datatables.net/responsive/2.2.1/css/responsive.dataTables.min.css' rel='stylesheet'>
 <link type="text/css" href='https://cdn.datatables.net/buttons/1.5.1/css/buttons.dataTables.min.css' rel='stylesheet'>

</head>
<body>

 <nav class="navbar navbar-default navbar-static-top">
  <div class="container-fluid">
   <div class="navbar-header">
    <a class="navbar-brand" href="https://www.tutorialswb.com/">TutorialsWB</a>
   </div>
  </div>
 </nav>
 <div class="container">
  <div class="messages"></div>
  <button class="btn btn-primary pull pull-right" data-toggle="modal" data-target="#addMember" onclick="addMemberModel()">
   Add Member
  </button>
  <br/><br/>

  <table id="manageMemberTable" class="display responsive nowrap" style="width:100%">
   <thead>
    <tr>
     <th>Name</th>
     <th>Age</th>
     <th>Contact</th>
     <th>Address</th>
     <th>Options</th>
    </tr>
   </thead>
  </table>
 </div>

 <!-- add member -->
 <div class="modal fade" tabindex="-1" role="dialog" id="addMember">
  <div class="modal-dialog" role="document">
   <div class="modal-content">
    <div class="modal-header">
     <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
     <h4 class="modal-title">Add Member</h4>
    </div>
    <form method="post" action="index.php/welcome/create" id="createForm">
     <div class="modal-body">        
      <div class="form-group">
       <label for="fname">First Name * </label>
       <input type="text" class="form-control" id="fname" name="fname" placeholder="First Name">
      </div>
      <div class="form-group">
       <label for="lname">Last Name</label>
       <input type="text" class="form-control" id="lname" name="lname" placeholder="Last Name">
      </div> 
      <div class="form-group">
       <label for="age">Age * </label>
       <input type="text" class="form-control" id="age" name="age" placeholder="Age">
      </div> 
      <div class="form-group">
       <label for="contact">Contact * </label>
       <input type="text" class="form-control" id="contact" name="contact" placeholder="Contact">
      </div> 
      <div class="form-group">
       <label for="address">Address</label>
       <input type="text" class="form-control" id="address" name="address" placeholder="Address">
      </div> 
     </div>
     <div class="modal-footer">
      <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      <button type="submit" class="btn btn-primary">Save changes</button>
     </div>
    </form>
   </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
 </div><!-- /.modal -->
 <!-- /add mmebers -->

 <!-- edit member -->
 <div class="modal fade" tabindex="-1" role="dialog" id="editMemberModal">
  <div class="modal-dialog" role="document">
   <div class="modal-content">
    <div class="modal-header">
     <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
     <h4 class="modal-title">Edit Member</h4>
    </div>
    <form method="post" action="index.php/welcome/edit" id="editForm">
     <div class="modal-body">        
      <div class="form-group">
       <label for="editFname">First Name * </label>
       <input type="text" class="form-control" id="editFname" name="editFname" placeholder="First Name">
      </div>
      <div class="form-group">
       <label for="editLname">Last Name</label>
       <input type="text" class="form-control" id="editLname" name="editLname" placeholder="Last Name">
      </div> 
      <div class="form-group">
       <label for="editAge">Age * </label>
       <input type="text" class="form-control" id="editAge" name="editAge" placeholder="Age">
      </div> 
      <div class="form-group">
       <label for="editContact">Contact * </label>
       <input type="text" class="form-control" id="editContact" name="editContact" placeholder="Contact">
      </div> 
      <div class="form-group">
       <label for="editAddress">Address</label>
       <input type="text" class="form-control" id="editAddress" name="editAddress" placeholder="Address">
      </div> 
     </div>
     <div class="modal-footer">
      <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      <button type="submit" class="btn btn-primary">Save changes</button>
     </div>
    </form>
   </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
 </div><!-- /.modal -->
 <!-- /edit mmebers -->

 <!-- removeMember -->
 <div class="modal fade" tabindex="-1" role="dialog" id="removeMemberModal">
  <div class="modal-dialog" role="document">
   <div class="modal-content">
    <div class="modal-header">
     <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
     <h4 class="modal-title">Modal title</h4>
    </div>
    <div class="modal-body">
     <p>Do you really want to remove ?</p>
    </div>
    <div class="modal-footer">
     <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
     <button type="button" id="removeMemberBtn" class="btn btn-primary">Delete</button>
    </div>
   </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
 </div><!-- /.modal -->
 <!-- removeMember -->
 
 <!-- jquery -->
 <script type="text/javascript" src="assets/jquery/jquery.min.js"></script>
 <!-- bootstrap js -->
 <script type="text/javascript" src="assets/bootstrap/js/bootstrap.min.js"></script>
 <!-- datatables -->
 <!-- custom js -->
 <script type="text/javascript" src="custom/js/home.js"></script>


 <!--Script Javascript-->
 <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
 <script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
 <script src="https://cdn.datatables.net/responsive/2.2.1/js/dataTables.responsive.min.js"></script>
 <script src="https://cdn.datatables.net/buttons/1.5.1/js/dataTables.buttons.min.js"></script>
 <script src="https://cdn.datatables.net/buttons/1.5.1/js/buttons.colVis.min.js"></script>
 <script>
  $(document).ready(function() {
   $('#example').DataTable( {
    dom: 'Bfrtip',
    buttons: [
    'colvis'
    ]
   } );
  } );
 </script>
</body>
</html> 

Kalian bisa mendownload file langsung dibawah ini, kalian bisa memodifikasi sebgaai baahan untuk pembelajaran untuk menambah pengetahuan.


Sebelumnya kami mohon maaf karena kami tidak menelaskan satu per satu, fungsi demi fungsi yang ada pada folder controllers dan folder models karena ini itu sangat panjang, tetapi jika teman-teman mempunyai pertanyaan sekitar apa yang kamis bahas di atas silahkan tinggalkan komentar dibawah.


close