CRUD CodeIgniter 3 + Bootstrap 4

CRUD CodeIgniter 3 + Bootstrap 4

Tutorial CRUD Codeigniter: Insert (tambah data), edit / update & hapus dengan Xampp database mysql.

Materi belajar Codeigniter dasar pemula untuk sistem CRUD sederhana dengan menggunakan konsep MVC + design template Bootstrap 4.

Materi latihan Pasang template Bootstrap + CI: Baca disini

Kita akan belajar / latihan Codeigniter dengan basis data (database) mysql dengan PHPmyadmin xampp / Localhost, materi ini cocok untuk kamu yang baru belajar CI.

Update: Versi Codeigniter yang digunakan adalah: 3.xx

 

Belajar CRUD Codeigniter

Crud adalah dasar codeigniter dari semua projects aplikasi dimana setiap fitur nantinya akan ada input, edit, update & hapus data yang disimpan pada database.

Latihan CRUD Codeigniter: buat folder baru > xampp > hddocs > latihanCI

  • URL: http://localhost/latihanCI

Note: file codeigniter 3 & template kita menggunakan materi latihan: sebelumnya »

Selanjutnya Langsng mulai, temen2,

Buat database baru: latihan_ci > tabel: user

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";

CREATE TABLE `user` (
  `id` int(5) NOT NULL,
  `name` varchar(100) NOT NULL,
  `email` varchar(150) NOT NULL,
  `phone` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `user`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `user`
  MODIFY `id` int(5) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=22;
COMMIT;

Koneksi Database + Codeigniter: 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' => 'root',
  'password' => '',
  'database' => 'latihan_ci',
  '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
);

 

Seting Routes: application/config/routes.php

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

$route['default_controller'] = 'crud';
$route['404_override'] = '';
$route['translate_uri_dashes'] = TRUE;

ket: fungsi routes untuk seting default halaman home, saat url dibuka, Infomasi lengkap setingan / konfigurasi dasar codeigniter bisa agan pelajari disini:

READ :  Cara Konfigurasi Seting Dasar CodeIgniter 3

 

Seting autoload: application/config/autoload.php

$autoload['libraries'] = array('session', 'database', 'form_validation','template');
$autoload['helper'] = array('url', 'form');

 

Buat file controller CRUD: Crud.php

lokasi folder: application/controllers/Crud.php

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

class Crud extends CI_Controller {

  public function __construct()
  {
    parent::__construct();
    $this->load->model('m_crud');

  }

  // List all data
  public function index()
  {
     $data['tmp']= $this->m_crud->tampil()->result();
     $this->template->load('role','crud/view',$data);
  }

  // Add a form item
  public function form_add()
  {
     $this->template->load('role','crud/create');
  }
    
    // ada data proses input
  public function add()
  {
     
     $this->form_validation->set_rules('name', 'name', 'trim|required|min_length[3]|max_length[45]');
     $this->form_validation->set_rules('email', 'email', 'trim|required|min_length[5]|max_length[45]');
     $this->form_validation->set_rules('phone', 'Phone', 'trim|required|min_length[5]|max_length[14]');
     
     if ($this->form_validation->run() == TRUE) 
     {
     	if($this->m_crud->input())
            {
            $this->session->set_flashdata('pesan','Add data succesfuly!');
            redirect('crud','refresh');
            }
     } else {
        $this->template->load('role','crud/create');
            }

  }

  public function edit(){

     $data['tmp']=$this->m_crud->m_edit()->row();
     $this->template->load('role','crud/edit',$data);

  }

  //Update one item
  public function update()
  {

   $this->form_validation->set_rules('name', 'name', 'trim|required|min_length[3]|max_length[45]');
     $this->form_validation->set_rules('email', 'email', 'trim|required|min_length[5]|max_length[45]');
     $this->form_validation->set_rules('phone', 'Phone', 'trim|required|min_length[5]|max_length[14]');
      
      if ($this->form_validation->run() == TRUE) 
      {
     if($this->m_crud->m_update()){
                $this->session->set_flashdata('pesan','Update data succesfuly!');
                redirect('/','refresh');
        }else{

     	        $this->session->set_flashdata('pesan','Update data failed');
                redirect('/','refresh');

              }

    }else{

    	$data['tmp']=$this->m_crud->m_edit()->row();
        $this->template->load('role','crud/edit',$data);
         
         }

    }

  //Delete one item
  public function del()
  {

     if($this->m_crud->delete())
     {
                $this->session->set_flashdata('pesan','Delete data succesfuly!');
                redirect('crud','refresh');
     }else{

     	        $this->session->set_flashdata('pesan','Delete data failed');
                redirect('crud','refresh');

          }

  }
}

/* End of file Crud.php */
/* Location: ./application/controllers/Crud.php */

Ketengan kode:

semua kode function tampil data, edit data & hapus data kita buat 1 file controllers Crud.php didalam kode telah kita tambahkan form_validasi & flash_data untuk notifikasi proses.

 

Buat file Model Crud: M_crud.php

lokasi folder: application/models/M_crud.php

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

class M_crud extends CI_Model {

  
  public function input(){
    $data = array('name' => $this->input->post('name') , 
                  'email'=> $this->input->post('email'),
                  'phone'=> $this->input->post('phone'));
    return $this->db->insert('user',$data);
  }

  public function tampil(){
    $this->db->select('*');
  return $this->db->get('user');
  }

  public function delete(){

        $this->db->where('id',$this->uri->segment(3));
        return $this->db->delete('user');

  }

  public function m_edit(){

    $this->db->select('*');
    $this->db->where('id',$this->uri->segment(3));
  return $this->db->get('user');
  
  }

  public function m_update(){

    $data = array('name' => $this->input->post('name') , 
                  'email'=> $this->input->post('email'),
                  'phone'=> $this->input->post('phone'));

        $this->db->where('id',$this->uri->segment(3));
        return $this->db->update('user',$data);

  }

}

/* End of file M_crud.php */
/* Location: ./application/models/M_crud.php */

keterangan kode:

Dalam proses edit & hapus data kita menggunakan identifikasi variable ID field, sehingga kita pakai uri-sement(3),

Sample include URL varibale ID: http://localhost/latihanCI/crud/edit/12

 

Buat folder “crud” didalam folder view, yang berisi file:

  1. view.php
  2. create.php
  3. edit.php

 

kode view.php:

<div class="col-md-8">
<h1 class="my-4">Views
          <small>Data sample</small>
        </h1>

<?php echo anchor('crud/form_add', '+ Add data', 'class="btn btn-primary btn-sm"'); ?>
<br><br>
<font color="green"><?php echo $this->session->flashdata('pesan'); ?></font>

<table class="table">
  <thead>
    <tr>
      <th scope="col">#ID</th>
      <th scope="col">Name</th>
      <th scope="col">Email</th>
      <th scope="col">Phone</th>
      <th scope="col">Option</th>
    </tr>
  </thead>

  <tbody>
    <?php foreach ($tmp as $key) { ?>
    <tr>
      <th scope="row"><?php echo $key->id; ?></th>
      <td><?php echo $key->name; ?></td>
      <td><?php echo $key->email; ?></td>
      <td><?php echo $key->phone; ?></td>
      <td>
        <?php echo anchor('crud/edit/'.$key->id, 'Edit', 'class="badge badge-info"');  ?>
        /
        <?php echo anchor('crud/del/'.$key->id, 'Delete',array('class'=>'badge badge-danger', 'onclick'=>"return confirmDialog();"));  ?>
     </td>
    </tr>
   <?php }?>
  </tbody>
</table>
</div>

<script type="text/javascript">
function confirmDialog() {
  var x=confirm("Yakin akan di hapus?")
  if (x) {
    return true;
  } else {
    return false;
  } }
</script>

Note: menambahkan fungsi javascript untuk validasi (yes/no) tombol / link hapus data!

 

Kode create.php:

  <div class="col-md-4">

        <h1 class="my-4">Add
          <small>Data sample</small>
        </h1>

  <font color="green"><?php echo $this->session->flashdata('pesan'); ?></font>
  <?php echo form_open('crud/add',''); ?>
  <div class="form-group">
    <label for="exampleInputEmail1">Name</label>
    <input type="text" name="name"class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp">
    <?php echo form_error('name', '<div class="text-danger"><small>', '</small></div>');?>
  </div>

  <div class="form-group">
    <label for="exampleInputPassword1">Email</label>
    <input type="email" name="email" class="form-control" id="exampleInputPassword1">
    <?php echo form_error('email', '<div class="text-danger"><small>', '</small></div>');?>
  </div>

  <div class="form-group">
    <label for="exampleInputPassword1">Phone</label>
    <input type="text" name="phone" class="form-control" id="exampleInputPassword1">
    <?php echo form_error('phone', '<div class="text-danger"><small>', '</small></div>');?>
  </div>

  <button type="submit" class="btn btn-primary">Submit</button>
<?php echo form_close(); ?>
</div>

 

kode edit.php:

  <div class="col-md-4">

        <h1 class="my-4">Edit
          <small>Data sample</small>
        </h1>
        
  <font color="green"><?php echo $this->session->flashdata('pesan'); ?></font>
  <?php echo form_open('crud/update/'.$tmp->id,''); ?>

  <div class="form-group">
    <label for="exampleInputEmail1">Name</label>
    <input type="text" name="name" class="form-control" value="<?php echo $tmp->name; ?>">
    <?php echo form_error('name', '<div class="text-danger"><small>', '</small></div>');?>
  </div>

  <div class="form-group">
    <label for="exampleInputPassword1">Email</label>
    <input type="email" name="email" class="form-control" value="<?php echo $tmp->email; ?>">
    <?php echo form_error('email', '<div class="text-danger"><small>', '</small></div>');?>
  </div>

  <div class="form-group">
    <label for="exampleInputPassword1">Phone</label>
    <input type="text" name="phone" class="form-control" value="<?php echo $tmp->phone; ?>">
    <?php echo form_error('phone', '<div class="text-danger"><small>', '</small></div>');?>
  </div>

  <button type="submit" class="btn btn-primary">Update Now!</button>
<?php echo form_close(); ?>

</div>

 

Discliamer

  • Penjelaskan secara rinci makna setiap baris kode pada masing controller, model & views
  • Keterangan & fungsi setiap baris kode akan kita bahas pada video diatas.
  • CRUD Codeigniter menggunakan konsep full MVC
  • hasil masih sederhana jadi bisa dikembangkan lebih lengkap

 

Next Belajar CI ?

Materi latihan codeigniter selanjutnya kita akan belajar cara membuat sistem login CI sederhana + Secure dengan enkirpsi password hash.

READ :  Login, Register CodeIgniter3 (Hash BCRYPT) + Bootstrap4

__Semoga bermanfaat & selamat beajar!