Categories
PHP

Aplikasi Crud PHP Menggunakan CodeIgniter

crud php

Aplikasi CRUD (Create, Read, Update, dan Deleted) merupakan dasar-dasar
yang sangat umum dalam pengembangan web. Ketika seseorang menginginkan menjadi web developer maka mereka wajib menguasai atau setidaknya menegtahui bagaimana membuat sistem Crud PHP.

CRUD adalah dasar inti yang digunakan secara umum dalam membuat suatu sistem, nah kali ini kami akan share bagaimana membuat Aplikasi Crud PHP menggunakan CodeIgniter.

Langsung saja mari kita masuk kedalam pembahasan intinya.

1. Base URL – buka file config yaitu pada application / config / config.php

$config['base_url'] = 'http://localhost:9080/cicrud';

2. 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 ;

3. Koneksi Database – buka file databse pada application / config/ database.php kemudian masukkan nama database anda.

$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
);

4. Controllers – Buat file welcome.php pada folder controllers

<?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);
  }
 }


}

5. 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
 }
 
}

6. 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://jasawebsite.ooo">jasawebsite</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">×</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">×</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">×</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 filenya langsung pada link button di bawah ini.

Sekian share kali ini jika kalian masih paham silahkan tinggalkan komentar di bawah dan mulai berdiskusi dengan kami.

Leave a Reply

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