Home » Codeigniter » Tutorial CRUD di CodeIgniter 3 : Aplikasi Sederhana

Tutorial CRUD di CodeIgniter 3 : Aplikasi Sederhana

by Bagus Dharma Iswara
by Bagus Dharma Iswara

Kali ini kita akan mencoba untuk membahas materi mengenai Berkenalan dengan Database pada CodeIgniter 3. Kalau teman-teman belum sempat mengikuti seri tutorial mengenai CodeIgniter 3 ini dapat dimulai saja untuk melihat dari awal di Berkenalan dengan Web Framework CodeIgniter!.

Kalau berbicara mengenai Berkenalan dengan Database pada CodeIgniter 3 maka kita pasti akan membahas mengenai fitur CRUD (Create, Read, Update dan Delete) pada Web Framework. Baik langsung saja kita mulai mengenai pembahasannya.

Mempersiapkan Database Pendukung

Yang pertama kali harus teman-teman lakukan adalah mempersiapkan sebuah database dengan nama tutorial_db. Perlu diperhatikan disini bahwa penamaan database ini adalah sebuah contoh, dan penamaan database ini dapat dibuat sesuai kebutuhan atau bebas.

kalau teman-teman belum memahami mengenai cara membuat sebuah database, maka dapat belajar kembali pada materi SQL agar lebih mudah untuk memahaminya. Kalau sudah memahami mengenai materi SQL, maka dapat mengikuti tutorial ini dengan baik.

Membuat database dapat dilakukan dengan menuliskan kode berikut

CREATE DATABASE tutorial_db;

Statement kueri ini berarti kita akan membuat sebuah database dengan nama tutorial_db. Selanjutnya kita dapat membuat sebuah tabel dengan nama customer dengan struktur tabel sebagai berikut :

  1. customer_id.
  2. customer_firstname.
  3. customer_lastname.

Kita dapat menuliskan atau mengeksekusi kueri berikut untuk menghasilkan tabel berdasarkan struktur diatas

CREATE TABLE customer(
customer_id INT PRIMARY KEY AUTO_INCREMENT,
customer_firstname VARCHAR(20),
customer_lastname VARCHAR(20)
);

pada bagian pertama, untuk customer_id dapat dibuat dengan tipe data Integer atau Int dengan menjadikannya sebuah Primary Key dan Auto Increment. Untuk ID biasanya kita gunakan sebuah Primary Key dan Auto Increment untuk memudahkan programmer.

Selanjutnya kita dapat menambahkan beberapa data dummy atau data yang kita buat sendiri menggunakan fungsi SQL INSERT INTO.

INSERT INTO customer(customer_firstname,customer_lastname) VALUES
('Andi','Surya'),
('Budi','Adi'),
('Darma','Surya'),
('Sutanto','Rahman'),
('Sakura','Bunga'),
('Mawar','Ayu'),
('Kintan','Agung'),
('Bulan','Dewi'),
('Adena','Rahayu'),
('Wulan','Dari'),
('Lestari','Trisna');

Koneksi Database dengan CodeIgniter 3

Database sudah dibuat sebelumnya, maka sekarang saatnya kita untuk mengkoneksikan database yang sudah ada dengan CodeIgniter 3. Cara mengkoneksikan CodeIgniter 3 ini dengan database sangat sederhana dengan membuka file database.php. File ini berada pada direktori application/config/database.php.

File database.php dapat dibuka dengan text editor yang teman-teman gunakan saat ini, atau kalau belum memiliki text editor maka dapat membaca rekomendasi kami mengenai text editor pada Text Editor Gratis Terbaik: Ringan dan Powerful.

$active_group = 'default';
$query_builder = TRUE;
 
$db['default'] = array(
    'dsn'   => '',
    'hostname' => 'localhost',
    'username' => '',
    'password' => '',
    'database' => '',
    '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
);

Dapat kita setting atau ganti dengan

$active_group = 'default';
$query_builder = TRUE;
 
$db['default'] = array(
    'dsn'   => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => '',
    'database' => 'tutorial_db',
    '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
);

Kalau sudah diganti, coba kembali project yang telah dibuat pada browser kalau tidak ada pemberitahuan error maka langkah yang sudah dikerjakan sudah benar dan database sudah berhasil terkoneksi dengan CodeIgniter 3.

Menampilkan Data Hasil Pembuatan Database Sebelumnya (Read) ke Dalam View CodeIgniter 3

Saat ini kita sudah memiliki database yang telah terkoneksi dengan CodeIgniter 3, maka pertanyaan selanjutnya adalah bagaimana cara menampilkannya ke dalam tampilan View pada CodeIgniter 3.

1. Membuat Model

Hal pertama yang harus kita lakukan adalam membuat sebuah model dengan nama Customer_model.php di dalam folder models atau biasanya berada pada direktori application/models.

Ubah atau tambahkan file Customer_model.php dengan kode berikut pada text editor

<?php
class Customer_model extends CI_Model{
 
  function get_customer(){
    $result = $this->db->get('customer');
    return $result;
  }
   
}

Sedikit penjelasan disini adalah pada model kita dapat menggunakan fungsi get() dari database yang biasanya digunakan mengambil data langsung pada database. Pada kode $this->db->get(‘customer’) ini berarti kita mengambil data tabel dari customer yang telah dibuat sebelumnya dengan nama tabel customer. untuk penjelasan penulisan class dan nama fungsi seperti diatas bisa dicoba membaca kembali pada Membuat Aplikasi Hello World pada CodeIgniter 3.

2. Membuat Controller

Membuat File Controller dengan nama Customer.php, perlu diingat disini penamaan harus diawali dengan huruf awal CAPITAL. Lokasi file controller berada pada direktori application/controller. Kalau teman-teman masih bingung mengenai Controller dapat membaca pada materi Membuat Controller dan View pada CodeIgniter 3.

Pada file Customer.php kita dapat menambahkan kode berikut pada text editor

<?php
class Customer extends CI_Controller{
  function __construct(){
    parent::__construct();
    $this->load->model('customer_model');
  }
  function index(){
    $data['customer'] = $this->customer_model->get_customer();
    $this->load->view('customer_view',$data);
  }
}

Dapat dilihat pada fungsi __construct() berisi kode $this->load->model(‘customer_model’); ini berarti kita bisa memanggil model customer_model secara otomatis.

3. Membuat View

Langkah ketiga, kita dapat membuat sebuah file View dengan nama customer_view.php yang kemudian dapat kita tuliskan kode berikut

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Nama Pelanggan</title>
    <!-- ini bagian load bootstrap css file -->
    <link href="<?php echo base_url('assets/css/bootstrap.min.css');?>" rel="stylesheet">
    <!-- selesai load bootstrap css file -->
  </head>
  <body>
 
    <div class="container">
        <h1><center>Nama Pelanggan</center></h1>
      <table class="table table-striped">
        <thead>
          <tr>
            <th scope="col">#</th>
            <th scope="col">Nama Pertama</th>
            <th scope="col">Nama Kedua</th>
          </tr>
        </thead>
        <?php
          $count = 0;
          foreach ($customer->result() as $row) :
            $count++;
        ?>
          <tr>
            <th scope="row"><?php echo $count;?></th>
            <td><?php echo $row->customer_firstname;?></td>
            <td><?php echo $row->customer_lastname;?></td>
          </tr>
        <?php endforeach;?>
        </tbody>
      </table>
 
    </div>
 
    <!-- ini bagian load jquery js file -->
    <script src="<?php echo base_url('assets/js/jquery.min.js');?>"></script>
    <!-- ini bagian load bootstrap js file -->
    <script src="<?php echo base_url('assets/js/bootstrap.min.js');?>"></script>
    <!-- selesai load bootstrap js file -->
  </body>
</html>

Ketiga file yang dibutuhkan sudah lengkap mulai dari controller, model dan view sudah dibuat sekarang saatnya untuk mengecek kembali hasil yang telah dibuat.

Kita dapat menjalankan Controller Customer pada browser kita dengan menuliskan alamat localhost/tutorialCI/customer. Ketika berhasil dijalankan maka akan menampilkan tampilan tabel yang berisi data dummy dari database yang telah kita buat.

Menambahkan Data Baru (Create) ke Dalam Database pada CodeIgniter 3

Sebelumnya kita sudah berhasil dalam menampilkan atau mengambil data-data yang ada pada database tutorial_db dan mengambil data dari tabel customer. Kali ini kita akan mencoba untuk Menambahkan data baru ke dalam database dengan fungsi CRUD melalui fungsi CREATE.

1. Membuat Model

Hal pertama yang kita lakukan adalah membuka nama model yang telah kita buat sebelumnya pada model Customer_model.php. Kita dapat menambahkan kode berikut

<?php
class Customer_model extends CI_Model{
 
  function get_customer(){
    $result = $this->db->get('customer');
    return $result;
  }
  function add_data($customer_firstname,$customer_lastname){
    $data = array(
      'customer_firstname' => $customer_firstname,
      'customer_lastname' => $customer_lastname
    );
    $this->db->insert('customer',$data);
  }
   
}

kita dapat melihat bahwa kita telah menggunakan fungsi INSERT dari database yang dapat dilihat pada kode $this->db->insert(‘customer’,$data);

2. Membuat Controller

Setelah membuat model untuk menambahkan data, kita dapat membuka kembali controller yang telah dibuat sebelumnya yaitu controller Costumer.php

Kita dapat menambahkan beberapa kode berikut kedalam controller Customer.php

<?php
class Customer extends CI_Controller{
  function __construct(){
    parent::__construct();
    $this->load->model('customer_model');
  }
  function index(){
    $data['customer'] = $this->customer_model->get_customer();
    $this->load->view('customer_view',$data);
  }
  function add_data(){
    $this->load->view('add_customer_view');
  }
  function save_data(){
    $customer_firstname = $this->input->post('customer_firstname');
    $customer_lastname = $this->input->post('customer_lastname');
    $this->customer_model->add_data($customer_firstname,$customer_lastname);
    redirect('customer');
  }
}

Catatan : ada beberapa kode yang baru pada fungsi save_data(). kita kenali satu persatu

  1. Berisi kode $this->input->post(‘customer_firstname’); ini berarti kita dapat menambahkan data kedalam tabel customer pada kolom customer_firstname dengan metode atau cara penggunaan fungsi dari HTTP yaitu POST.
  2. Berisi kode $this->input->post(‘customer_lastname’); ini berarti kita dapat menambahkan data kedalam tabel customer pada kolom customer_lastname dengan metode atau cara penggunaan fungsi dari HTTP yaitu POST.
  3. Berisi kode $this->customer_model->add_data($customer_firstname,$customer_lastname); ini berarti kita mengambil fungsi dari model customer_model yang telah kita buat sebelumnya. Pada model ini kita memiliki sebuah fungsi bernama add_data() untuk melakukan insert data.
  4. Berisi kode redirect(), ini berarti kita menggunakan fungsi untuk kembali pada controller dalam hal ini kita kembali pada controller customer.

3. Membuat View

Untuk view kita dapat membuat baru dengan nama add_customer_view.php dengan menuliskan kode berikut

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Tambah Nama Customer</title>
    <!-- load bootstrap css file -->
    <link href="<?php echo base_url('assets/css/bootstrap.min.css');?>" rel="stylesheet">
  </head>
  <body>
 
    <div class="container">
      <h1><center>Tambah Nama Customer</center></h1>
        <div class="col-md-6 offset-md-3">
        <form action="<?php echo site_url('customer/save_data');?>" method="post">
          <div class="form-group">
            <label>First Name Customer</label>
            <input type="text" class="form-control" name="customer_firstname" placeholder="First Name">
          </div>
          <div class="form-group">
            <label>Last Name Customer</label>
            <input type="text" class="form-control" name="customer_lastname" placeholder="Last Name">
          </div>
          <button type="submit" class="btn btn-primary">Submit</button>
        </form>
      </div>
    </div>
 
    <!-- load jquery js file -->
    <script src="<?php echo base_url('assets/js/jquery.min.js');?>"></script>
    <!-- load bootstrap js file -->
    <script src="<?php echo base_url('assets/js/bootstrap.min.js');?>"></script>
  </body>
</html>

Dapat dilihat pada browser dengan menuliskan alamat berikut localhost/tutorialCI/customer/add_data.

Menghapus Data (Delete) pada CodeIgniter 3

Hal yang tidak kalah penting adalah bagian meghapus data atau DELETE. Kita buka kembali file view customer_view.php yang sudah dibuat. File tersebut dapat diganti dengan

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Nama Pelanggan</title>
    <!-- ini bagian load bootstrap css file -->
    <link href="<?php echo base_url('assets/css/bootstrap.min.css');?>" rel="stylesheet">
    <!-- selesai load bootstrap css file -->
  </head>
  <body>
 
    <div class="container">
        <h1><center>Nama Pelanggan</center></h1>
      <table class="table table-striped">
        <thead>
          <tr>
            <th scope="col">#</th>
            <th scope="col">Nama Pertama</th>
            <th scope="col">Nama Kedua</th>
            <th width="200">Action</th>
          </tr>
        </thead>
        <?php
          $count = 0;
          foreach ($customer->result() as $row) :
            $count++;
        ?>
          <tr>
            <th scope="row"><?php echo $count;?></th>
            <td><?php echo $row->customer_firstname;?></td>
            <td><?php echo $row->customer_lastname;?></td>
            <td>
                <a href="<?php echo site_url('customer/delete/'.$row->customer_id);?>" class="btn btn-sm btn-danger">Delete</a>
            <td>
          </tr>
        <?php endforeach;?>
        </tbody>
      </table>
 
    </div>
 
    <!-- ini bagian load jquery js file -->
    <script src="<?php echo base_url('assets/js/jquery.min.js');?>"></script>
    <!-- ini bagian load bootstrap js file -->
    <script src="<?php echo base_url('assets/js/bootstrap.min.js');?>"></script>
    <!-- selesai load bootstrap js file -->
  </body>
</html>

Pada view diatas kita menambah 1 buah kolom lagi bernama action yang berisi tombol delete. pada tombol ini kita mengambil ID dari customer. dan teman-teman dapat melihat kembali pada browser untuk melihat perubahan pada tampilan tabel.

Edit Controller

Disini kita akan menambahkan fungsi untuk melakukan delete data pada controller Customer.php dengan menambahkan kode berikut

<?php
class Customer extends CI_Controller{
  function __construct(){
    parent::__construct();
    $this->load->model('customer_model');
  }
  function index(){
    $data['customer'] = $this->customer_model->get_customer();
    $this->load->view('customer_view',$data);
  }
  function add_data(){
    $this->load->view('add_customer_view');
  }
  function save_data(){
    $customer_firstname = $this->input->post('customer_firstname');
    $customer_lastname = $this->input->post('customer_lastname');
    $this->customer_model->add_data($customer_firstname,$customer_lastname);
    redirect('customer');
  }
  function delete(){
    $customer_id = $this->uri->segment(3);
    $this->customer_model->delete($customer_id);
    redirect('product');
  }
}

Edit Model

Kemudian kita harus menambahkan pada file Customer_model.php dengan menambahkan kode berikut

<?php
class Customer_model extends CI_Model{
 
  function get_customer(){
    $result = $this->db->get('customer');
    return $result;
  }
  function add_data($customer_firstname,$customer_lastname){
    $data = array(
      'customer_firstname' => $customer_firstname,
      'customer_lastname' => $customer_lastname
    );
    $this->db->insert('customer',$data);
  }
   
function delete($customer_id){
    $this->db->where('customer_id', $customer_id);
    $this->db->delete('customer');
   }
}

Maka fungsi hapus data akan telah dapat digunakan untuk menghapus data dengan bantuan ID dari customer.

Cara Update Data pada CodeIgniter 3

Kita telah berhasil membuat 3 Fungsi dari CRUD yaitu menampilkan data atau READ, membuat data baru atau CREATE dan menghapus data atau DELETE. yang terakhir kita akan membuat UPDATE atau memperbaharui data ke database.

Edit View

Buka kembali file view customer_view.php kemudian kita dapat mengubahnya menjadi sebagai berikut

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Nama Pelanggan</title>
    <!-- ini bagian load bootstrap css file -->
    <link href="<?php echo base_url('assets/css/bootstrap.min.css');?>" rel="stylesheet">
    <!-- selesai load bootstrap css file -->
  </head>
  <body>
 
    <div class="container">
        <h1><center>Nama Pelanggan</center></h1>
      <table class="table table-striped">
        <thead>
          <tr>
            <th scope="col">#</th>
            <th scope="col">Nama Pertama</th>
            <th scope="col">Nama Kedua</th>
            <th width="200">Action</th>
          </tr>
        </thead>
        <?php
          $count = 0;
          foreach ($customer->result() as $row) :
            $count++;
        ?>
          <tr>
            <th scope="row"><?php echo $count;?></th>
            <td><?php echo $row->customer_firstname;?></td>
            <td><?php echo $row->customer_lastname;?></td>
            <td>
                <a href="<?php echo site_url('customer/edit_data/'.$row->customer_id);?>" class="btn btn-sm btn-warning">Edit</a>
                <a href="<?php echo site_url('customer/delete/'.$row->customer_id);?>" class="btn btn-sm btn-danger">Delete</a>
            <td>
          </tr>
        <?php endforeach;?>
        </tbody>
      </table>
 
    </div>
 
    <!-- ini bagian load jquery js file -->
    <script src="<?php echo base_url('assets/js/jquery.min.js');?>"></script>
    <!-- ini bagian load bootstrap js file -->
    <script src="<?php echo base_url('assets/js/bootstrap.min.js');?>"></script>
    <!-- selesai load bootstrap js file -->
  </body>
</html>

Kita telah menambah sebuah tombol baru yaitu tombol Edit.

Edit Controller

Sekarang kita harus menambahkan kode berikut pada controller Customer.php

function edit_data(){
    $customer_id = $this->uri->segment(3);
    $result = $this->customer_model->get_customer_id($customer_id);
    if($result->num_rows() > 0){
        $i = $result->row_array();
        $data = array(
            'customer_id'    => $i['customer_id'],
            'customer_firstname'  => $i['customer_firstname'],
            'customer_lastname'     => $i['customer_lastname']
        );
        $this->load->view('edit_customer_view',$data);
    }else{
        echo "Data Was Not Found";
    }
}

Edit Model

Selanjutnya kita dapat menambahkan kode berikut pada model Customer_model.php

function get_customer_id($customer_id){
    $query = $this->db->get_where('customer', array('customer_id' => $customer_id));
    return $query;
}

Membuat View Baru

Kali ini kita akan membuat sebuah view baru dengan nama edit_customer_view.php dengan menuliskan kode berikut

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Edit Customer</title>
    <!-- load bootstrap css file -->
    <link href="<?php echo base_url('assets/css/bootstrap.min.css');?>" rel="stylesheet">
  </head>
  <body>
 
    <div class="container">
      <h1><center>Edit Customer Name</center></h1>
        <div class="col-md-6 offset-md-3">
        <form action="<?php echo site_url('customer/update');?>" method="post">
          <div class="form-group">
            <label>Customer First Name</label>
            <input type="text" class="form-control" name="customer_firstname" value="<?php echo $customer_firstname;?>" placeholder="First Name">
          </div>
          <div class="form-group">
            <label>Customer Last Name</label>
            <input type="text" class="form-control" name="customer_lastname" value="<?php echo $customer_lastname;?>" placeholder="Last Name">
          </div>
          <input type="hidden" name="customer_id" value="<?php echo $customer_id?>">
          <button type="submit" class="btn btn-primary">Update</button>
        </form>
      </div>
    </div>
 
    <!-- load jquery js file -->
    <script src="<?php echo base_url('assets/js/jquery.min.js');?>"></script>
    <!-- load bootstrap js file -->
    <script src="<?php echo base_url('assets/js/bootstrap.min.js');?>"></script>
  </body>
</html>

Edit Controller Kembali

kita harus menambahkan kembali sebuah fungsi update pada Controller Customer.php maka Controller akan menghasilkan sebuah isi file menjadi seperti ini

<?php
class Customer extends CI_Controller{
  function __construct(){
    parent::__construct();
    $this->load->model('customer_model');
  }
  function index(){
    $data['customer'] = $this->customer_model->get_customer();
    $this->load->view('customer_view',$data);
  }
  function add_data(){
    $this->load->view('add_customer_view');
  }
  function save_data(){
    $customer_firstname = $this->input->post('customer_firstname');
    $customer_lastname = $this->input->post('customer_lastname');
    $this->customer_model->add_data($customer_firstname,$customer_lastname);
    redirect('customer');
  }
  function delete(){
    $customer_id = $this->uri->segment(3);
    $this->customer_model->delete($customer_id);
    redirect('product');
  }
  function edit_data(){
    $customer_id = $this->uri->segment(3);
    $result = $this->customer_model->get_customer_id($customer_id);
    if($result->num_rows() > 0){
        $i = $result->row_array();
        $data = array(
            'customer_id'    => $i['customer_id'],
            'customer_firstname'  => $i['customer_firstname'],
            'customer_lastname'     => $i['customer_lastname']
        );
        $this->load->view('edit_customer_view',$data);
    }else{
        echo "Data Was Not Found";
    }
  }
 function update(){
    $customer_id = $this->input->post('customer_id');
    $customer_firstname= $this->input->post('customer_firstname');
    $customer_lastname= $this->input->post('customer_lastname');
        $this->customer_model->update($customer_id,$customer_firstname,$customer_lastname);
    redirect('customer');
 }
}

Edit Model Kembali

Edit kembali file Customer_model.php dengan menambahkan fungsi update pada model yang akan menjadi keseluruhan file seperti ini

<?php
class Customer_model extends CI_Model{
 
  function get_customer(){
    $result = $this->db->get('customer');
    return $result;
  }
  function add_data($customer_firstname,$customer_lastname){
    $data = array(
      'customer_firstname' => $customer_firstname,
      'customer_lastname' => $customer_lastname
    );
    $this->db->insert('customer',$data);
  }
   
function delete($customer_id){
    $this->db->where('customer_id', $customer_id);
    $this->db->delete('customer');
   }
   function get_customer_id($customer_id){
    $query = $this->db->get_where('customer', array('customer_id' =>   $customer_id));
    return $query;
  }
  function update($customer_id,$customer_firstname,$customer_lastname){
    $data = array(
      'customer_firstname' => $customer_firstname,
      'customer_lastname' => $customer_lastname
    );
    $this->db->where('customer_id', $customer_id);
    $this->db->update('customer', $data);
  }
}

Cek kembali pada browser jika tidak terdapat error maka langkah-langkah yang telah dibuat dengan benar

You may also like