PHP CodeIgniter 4 – Operasi CRUD dasar dengan database MySQL dengan contoh

0

Dalam tutorial PHP CodeIgniter 4 ini, saya akan memberi tahu Anda fungsi CRUD dasar dengan Database MySQL.

CRUD adalah singkatan dari Create, Read, Update, dan Delete database records.

Ini adalah salah satu tugas paling umum dalam pengembangan untuk membuat sesuatu di tabel, memperbarui beberapa informasi, membaca data dari tabel dan menghapus informasi.

Dalam contoh ini, saya akan menggunakan perpustakaan bootstrap untuk membuat daftar posting dan merender formulir untuk membuat dan mengedit posting.

Unduh & Konfigurasi Aplikasi Codeigniter 4

Pada langkah pertama, saya akan mengunduh versi baru Codeigniter 4, Buka tautan ini 
https://codeigniter.com/download dan unduh Codeigniter 4 dan unzip aplikasi ini di direktori kerja Anda dan ubah nama aplikasi menjadi mentah.

Jalankan perintah komposer untuk mengunduh dependensi.

Sekarang saya akan mengkonfigurasi url dasar di app /Config/App.php.

Konfigurasi Database dan Buat Tabel

Pada langkah ini, saya akan membuat database terlebih dahulu yang disebut crud dan membuat tabel post baru di database crud ini.

Anda dapat menjalankan kueri SQL di bawah ini untuk membuat tabel posting di database Anda.
CREATE TABLE `posts` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `title` varchar(255) NOT NULL,
 `description` text NOT NULL,
 `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
 `updated_at` timestamp NULL DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
Sekarang saya perlu memperbarui kredensial database di file konfigurasi database.

Saya perlu membuka app/Config/Database.php dan membuka file Database.php di editor.
public $default = [
		'DSN'      => '',
		'hostname' => 'localhost',
		'username' => 'root',
		'password' => '',
		'database' => 'crud',
		'DBDriver' => 'MySQLi',
		'DBPrefix' => '',
		'pConnect' => false,
		'DBDebug'  => (ENVIRONMENT !== 'production'),
		'cacheOn'  => false,
		'cacheDir' => '',
		'charset'  => 'utf8',
		'DBCollat' => 'utf8_general_ci',
		'swapPre'  => '',
		'encrypt'  => false,
		'compress' => false,
		'strictOn' => false,
		'failover' => [],
		'port'     => 3306,
	];

Buat Model

Pada langkah ini, saya akan membuat file model PostModel.php untuk berkomunikasi dengan tabel posting di app/Models/ direktori.

<?php 
namespace App\Models;
use CodeIgniter\Database\ConnectionInterface;
use CodeIgniter\Model;
 
class PostModel extends Model
{
    protected $table = 'posts';
 
    protected $allowedFields = ['title', 'description'];
}

Buat Controller

In this controller file, I will create some method to perform crud operation.

Pada langkah ini, saya akan membuat file pengontrol Posts.php di dalam direktori app/Controllers.

  • index() – metode ini digunakan untuk membuat daftar semua posting.
  • create() – metode ini digunakan untuk membuat formulir buat.
  • store() – metode ini digunakan untuk memasukkan posting baru ke dalam tabel.
  • edit() – metode ini digunakan untuk membuat formulir edit.
  • update() – metode ini digunakan untuk memperbarui informasi posting.
  • delete() – metode ini digunakan untuk menghapus informasi posting dari tabel database.
<?php namespace App\Controllers;
 
use CodeIgniter\Controller;
use App\Models\PostModel;
 
class Posts extends Controller
{
 
    public function index()
    {    
        
        $model = new PostModel();
 
        $data['posts'] = $model->orderBy('id', 'DESC')->findAll();
        
        return view('posts', $data);
    }    
 
    public function create()
    {    
        return view('create-post');
    }
 
    public function store()
    {  
 
        helper(['form', 'url']);
         
        $model = new PostModel();
 
        $data = [
 
            'title' => $this->request->getVar('title'),
            'description'  => $this->request->getVar('description'),
            ];
 
        $save = $model->insert($data);
 
        return redirect()->to( base_url('posts') );
    }
 
    public function edit($id = null)
    {
    
     $model = new PostModel();
     
     $data['post'] = $model->find($id);
      
     return view('edit-post', $data);
    }
 
    public function update()
    {  
 
        helper(['form', 'url']);
         
        $model = new PostModel();
 
        $id = $this->request->getVar('id');
        
        $data = [
 
            'title' => $this->request->getVar('title'),
            'description'  => $this->request->getVar('description'),
            ];
 
        $save = $model->update($id,$data);
 
        return redirect()->to( base_url('posts') );
    }
 
    public function delete($id = null)
    {
 
     $model = new PostModel();
 
     $data['post'] = $model->where('id', $id)->delete();
      
     return redirect()->to( base_url('posts') );
    }
}

Buat Views

Pada langkah ini, saya akan membuat file html masing-masing.

  • posts.php
  • create-post.php
  • edit-post.php

posts.php

<!doctype html>
<html lang="en">
  <head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>Codeigniter 4 CRUD Tutorial -  posts List Example - Expertphp.in</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css">

</head>
<body>
 
<div class="container mt-5">
    <a href="<?php echo base_url('posts/create') ?>" class="btn btn-sm btn-success">Create</a>
   
  <div class="row mt-3">
     <table class="table table-bordered" id="posts">
       <thead>
          <tr>
             <th>Id</th>
             <th>Title</th>
             <th>Description</th>
             <th>Action</th>
          </tr>
       </thead>
       <tbody>
          <?php if($posts): ?>
          <?php foreach($posts as $post): ?>
          <tr>
             <td><?php echo $post['id']; ?></td>
             <td><?php echo $post['title']; ?></td>
             <td><?php echo $post['description']; ?></td>
             <td>
              <a href="<?php echo base_url('posts/edit/'.$post['id']);?>" class="btn btn-sm btn-success">Edit</a>
              <a href="<?php echo base_url('posts/delete/'.$post['id']);?>" class="btn btn-sm btn-danger">Delete</a>
              </td>
          </tr>
         <?php endforeach; ?>
         <?php endif; ?>
       </tbody>
     </table>
  </div>
</div>
 
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
 
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js" type="text/javascript"></script>
 
<script>
    $(document).ready( function () {
      $('#posts').DataTable();
  } );
</script>
</body>
</html>

create-post.php

<!DOCTYPE html>
<html>
<head>
  <title>Codeigniter 4 CRUD Tutorial - Post Form With Validation Example</title>
 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
 
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>  
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/additional-methods.min.js"></script>
 
</head>
<body>
 <div class="container">
    <br>
    <?= \Config\Services::validation()->listErrors(); ?>
 
    <span class="d-none alert alert-success mb-3" id="res_message"></span>
 
    <div class="row">
      <div class="col-md-9">
        <form action="<?php echo base_url('posts/store');?>" name="post_form" id="post_form" method="post" accept-charset="utf-8">
 
          <div class="form-group">
            <label for="title">Title</label>
            <input type="text" name="title" class="form-control" id="title" placeholder="Please enter title">
             
          </div> 
 
          <div class="form-group">
            <label for="email">Description</label>
            <input type="text" name="description" class="form-control" id="email" placeholder="Please enter description">
             
          </div>   
 
          <div class="form-group">
           <button type="submit" id="send_form" class="btn btn-success">Submit</button>
          </div>
          
        </form>
      </div>
 
    </div>
  
</div>
 <script>
   if ($("#post_form").length > 0) {
      $("#post_form").validate({
      
    rules: {
      title: {
        required: true,
      },
  
      description: {
        required: true,       
      },   
    },
    messages: {
        
      title: {
        required: "Please enter title",
      },
      description: {
        required: "Please enter description",       
      }, 
    },
  })
}
</script>
</body>
</html>

edit-post.php

<!DOCTYPE html>
<html>
<head>
  <title>Codeigniter 4 CRUD Tutorial - Edit Post Form With Validation Example</title>
 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
 
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>  
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/additional-methods.min.js"></script>
 
</head>
<body>
 <div class="container">
    <br>
    <?= \Config\Services::validation()->listErrors(); ?>
 
    <span class="d-none alert alert-success mb-3" id="res_message"></span>
 
    <div class="row">
      <div class="col-md-9">
        <form action="<?php echo base_url('posts/update');?>" name="post_form" id="post_form" method="post" accept-charset="utf-8">
 
           <input type="hidden" name="id" class="form-control" id="id" value="<?php echo $post['id'] ?>">
 
          <div class="form-group">
            <label for="title">Title</label>
            <input type="text" name="title" class="form-control" id="title" placeholder="Please enter title" value="<?php echo $post['title'] ?>">
             
          </div> 
 
          <div class="form-group">
            <label for="description">Description</label>
            <input type="text" name="description" class="form-control" id="description" placeholder="Please enter description" value="<?php echo $post['description'] ?>">
             
          </div>   
 
          <div class="form-group">
           <button type="submit" id="send_form" class="btn btn-success">Submit</button>
          </div>
          
        </form>
      </div>
 
    </div>
  
</div>
<script>
   if ($("#post_form").length > 0) {
      $("#post_form").validate({
      
    rules: {
      title: {
        required: true,
      },
  
      description: {
        required: true,       
      },   
    },
    messages: {
        
      title: {
        required: "Please enter title",
      },
      description: {
        required: "Please enter description",       
      }, 
    },
  })
}
</script>
</body>
</html>

Sekarang Anda dapat menjalankan aplikasi di http://localhost/crud/public/posts

LEAVE A REPLY

Please enter your comment!
Please enter your name here