Thao tác CRUD trong ứng dụng Codeigniter 4 kèm với plug-in Datatables jQuery.

Ứng dụng hôm nay mình tạo là ứng dụng biên tập thao tác với cơ sở dữ liệu từ điển.

Các chủ đề sau sẽ được đề cập trong hướng dẫn này:

  • Cài đặt Codeigniter với gói composer hoặc tải trực tiếp về máy.
  • Tạo các khung nhìn để xử lý các hoạt động CRUD.
  • Triển khai Bootstrap 4 trong Codeigniter. Triển khai DataTables trong Codeigniter.
  • Thêm dữ liệu vào MySQL.
  • Lấy dữ liệu từ MySQL.
  • Cập nhật dữ liệu từ MySQL.
  • Xóa đối tượng khỏi cơ sở dữ liệu.
  • Bật bộ kiểm tra lỗi code.

Cài đặt Codeigniter với gói composer hoặc tải trực tiếp về máy.

composer:

composer create-project codeigniter4/appstarter

Hãy đổi tên và truy cập thư mục project của bạn

cd codeigniter-crud-example

Ngoài ra, bạn cũng có thể tải xuống thủ công ứng dụng Codeigniter 4.0.4.

Bật bộ kiểm tra lỗi code trong CodeIgniter

Mở theo đường dẫn thư mục app/Config/Boot/development.php và đặt display_errors thành 1 thay vì 0. Tương tự trong tệp app / app/Config/Boot/production.php.

Thêm dữ liệu vào MySQL

Bước này sẽ tạo liên kết đến cơ sở dữ liệu. Chúng tôi sẽ tạo một cơ sở dữ liệu mới tên là `demo`, tạo tên người dùng`test` trong MySQL và thiết lập kết nối cơ sở dữ liệu. Để duy trì thao tác kết nối liên tục, bạn có thể thực thi truy vấn SQL từ PHPMyAdmin để tạo bảng từ điển như sau.

CREATE TABLE `tudien` (
  `td_id` int(11) NOT NULL COMMENT 'Primary Key ID',
  `td_ts` varchar(100) CHARACTER SET utf8 NOT NULL COMMENT 'Slovak',
  `td_tv` varchar(255) CHARACTER SET utf8 NOT NULL COMMENT 'Tiếng Việt'
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='datatable demo table';

--
-- Đang đổ dữ liệu cho bảng `tudien`
--

INSERT INTO `tudien` (`td_id`, `td_ts`, `td_tv`) VALUES
(1, 'Ng Văn A', '[email protected]'),
(2, 'Lê Văn C', '[email protected]');

--
-- Chỉ mục cho các bảng đã đổ
--

--
-- Chỉ mục cho bảng `tudien`
--
ALTER TABLE `tudien`
  ADD PRIMARY KEY (`td_id`);

--
-- AUTO_INCREMENT cho các bảng đã đổ
--

--
-- AUTO_INCREMENT cho bảng `tudien`
--
ALTER TABLE `tudien`
  MODIFY `td_id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key', AUTO_INCREMENT=3;
COMMIT;

Lưu ý, bạn có thể thay đổi CHARSET=latin1 thành utf-8 để có thể nhập chữ cái tiếng việt.

Công việc tiếp theo là xác định chi tiết cơ sở dữ liệu (dbname, username, password) trong tệp application/config/database.php. Nó sẽ tạo ra sự gắn kết giữa Codeigniter và MySQL.

public $default = [
        'DSN'      => '',
        'hostname' => 'localhost',
        'username' => 'root',
        'password' => 'pass',
        'database' => 'demo',
        'DBDriver' => 'MySQLi',
        'DBPrefix' => '',
        'pConnect' => false,
        'DBDebug'  => (ENVIRONMENT !== 'development'),
        'cacheOn'  => false,
        'cacheDir' => '',
        'charset'  => 'utf8',
        'DBCollat' => 'utf8_general_ci',
        'swapPre'  => '',
        'encrypt'  => false,
        'compress' => false,
        'strictOn' => false,
        'failover' => [],
        'port'     => 3306,
	];

Tạo Model mới TudienModel.php

app/comtroller/TudienModel.php

<?php

namespace App\Models;

use CodeIgniter\Model;

class TudienModel extends Model
{
    protected $table = 'tudien';
    protected $primaryKey = 'td_id';
    protected $allowedFields = ['td_ts', 'td_tv'];
}

Tạo Controler mới

app/controller/TudienCRUD.php

<?php 
namespace App\Controllers;
use App\Models\TudienModel;
use CodeIgniter\Controller;

class TudienCrud extends Controller
{
    // show tudien list
    public function index(){
        $TudienModel = new TudienModel();
        $data['tudien'] = $TudienModel->orderBy('td_id', 'ASC')->findAll();
        return view('td_views', $data);
    }


    //

    public function index2(){
        $TudienModel = new TudienModel();
        $data['tudien'] = $TudienModel->orderBy('td_id', 'ASC')->findAll();
        return view('td_lists', $data);
    }


    // add form
    public function create(){
        return view('add_td');
    }
 
    // insert data
    public function store() {
        $TudienModel = new TudienModel();
        $data = [
            'td_ts' => $this->request->getVar('td_ts'),
            'td_tv'  => $this->request->getVar('td_tv'),
        ];
        $TudienModel->insert($data);
        return $this->response->redirect(site_url('/tudien-list'));
    }

    // show single data
    public function singleUser($id = null){
        $TudienModel = new TudienModel();
        $data['td_obj'] = $TudienModel->where('td_id', $id)->first();
        return view('td_edit', $data);
    }

    // update từ điểnn data
    public function update(){
        $TudienModel = new TudienModel();
        $id = $this->request->getVar('td_id');
        $data = [
            'td_ts' => $this->request->getVar('td_ts'),
            'td_tv'  => $this->request->getVar('td_tv'),
        ];
        $TudienModel->update($id, $data);
        return $this->response->redirect(site_url('/tudien-list'));
    }
 
    // delete single data
    public function delete($id = null){
        $TudienModel = new TudienModel();
        $data['user'] = $TudienModel->where('td_id', $id)->delete($id);
        return $this->response->redirect(site_url('/tudien-list'));
    }    
}

Cấu hình Routes

thêm đoạn code này vào giữa file app/Config/Routes.php

/**
 * --------------------------------------------------------------------
 * Router Setup
 * --------------------------------------------------------------------
 */
$routes->setDefaultNamespace('App\Controllers');
$routes->setDefaultController('TudienCrud');
$routes->setDefaultMethod('index');
$routes->setTranslateURIDashes(false);
$routes->set404Override();
$routes->setAutoRoute(true);

/**
 * --------------------------------------------------------------------
 * Route Definitions
 * --------------------------------------------------------------------
 */

// We get a performance increase by specifying the default
// route since we don't have to scan directories.

$routes->get('/', 'TudienCrud::index');
$routes->get('/index', 'TudienCrud::index');

// CRUD RESTful Routes
$routes->get('tudien-list', 'TudienCrud::index');
// add form
$routes->get('td-form', 'TudienCrud::create');
// submit form
$routes->post('td-submit-form', 'TudienCrud::store');
// view 1 td GET
$routes->get('edit-view/(:num)', 'TudienCrud::singleUser/$1');
// update 1 td POST
$routes->post('update', 'TudienCrud::update');
//  delete 1 td GET
$routes->get('delete/(:num)', 'TudienCrud::delete/$1');

//  View all td Style LISTSS
$routes->get('td-lists', 'TudienCrud::index2');

Tạo trang views

tạo vào thêm đoạn code bên dưới với file app/Views/add_td.php

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Từ điển - Add</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
    
</head>

<body>

    <div class="container mt-4">
        <div class="d-flex justify-content-end">
            <a href="<?php echo site_url('/td-form') ?>" class="btn btn-success mb-2 mx-2">Add Từ điển</a>
            <a href="<?php echo site_url('/td-lists') ?>" class="btn btn-success mb-2 mx-2">Từ điểnn Lists</a>
            <a href="<?php echo site_url('/tudien-list') ?>" class="btn btn-success mb-2 mx-2">Từ điểnn List</a>

        </div>

        <div class="container mt-5">
            <form method="post" id="add_create" name="add_create" action="<?= site_url('/td-submit-form') ?>">
                <div class="form-group">
                    <label>Tiếng Slovak</label>
                    <input type="text" name="td_ts" class="form-control">
                </div>

                <div class="form-group">
                    <label>Tiếng Việt</label>
                    <!-- <input type="text" name="td_tv" class="form-control"> -->
                    <textarea rows="7" name="td_tv" class="form-control"></textarea>
                </div>

                <div class="form-group">
                    <button type="submit" class="btn btn-primary btn-block">Update Data</button>
                </div>
            </form>
        </div>

        <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/jquery.validate.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/additional-methods.min.js"></script>
        <script>
        // if ($("#add_create").length > 0) {
        //   $("#add_create").validate({
        //     rules: {
        //       name: {
        //         required: true,
        //       },
        //       email: {
        //         required: true,
        //         maxlength: 60,
        //         email: true,
        //       },
        //     },
        //     messages: {
        //       name: {
        //         required: "Name is required.",
        //       },
        //       email: {
        //         required: "Email is required.",
        //         email: "It does not seem to be a valid email.",
        //         maxlength: "The email should be or equal to 60 chars.",
        //       },
        //     },
        //   })
        // }
        </script>
</body>

</html>

tạo và thêm đoạn code bên dưới app/Views/td_views.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 App Example - positronx.io</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
</head>
<body>

<div class="container mt-4">
<div class="d-flex justify-content-end">
        <a href="<?php echo site_url('/td-form') ?>" class="btn btn-success mb-2 mx-2">Add User</a>
        <a href="<?php echo site_url('/td-lists') ?>" class="btn btn-success mb-2 mx-2">User Lists</a>
        <a href="<?php echo site_url('/tudien-list') ?>" class="btn btn-success mb-2 mx-2">Index Users List</a>

   </div>
    <?php
     if(isset($_SESSION['msg'])){
        echo $_SESSION['msg'];
      }
     ?>
  <div class="mt-3 table-responsive">
     <table class="table table-striped table-bordered table-hover" id="tudien-list">
       <thead>
          <tr>
             <th>Id</th>
             <th>Tiếng Slovak</th>
             <th>Tiếng Việt</th>
             <th>Action</th>
          </tr>
       </thead>
       <tbody>
          <?php if($tudien): ?>
          <?php foreach($tudien as $row): ?>
          <tr>
             <td><?php echo $row['td_id']; ?></td>
             <td><?php echo $row['td_ts']; ?></td>
             <td><pre><?php echo $row['td_tv']; ?></pre></td>
             <td>
              <a href="<?php echo base_url('edit-view/'.$row['td_id']);?>" class="btn btn-primary btn-sm">Edit</a>
              <a href="<?php echo base_url('delete/'.$row['td_id']);?>" class="btn btn-danger btn-sm">Delete</a>
              </td>
          </tr>
         <?php endforeach; ?>
         <?php endif; ?>
       </tbody>
     </table>
  </div>
</div>
 
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<!-- <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css"> -->
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.min.css">


<!-- <script type="text/javascript" src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script> -->
<script type="text/javascript" src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"></script>


<script>
    $(document).ready( function () {
      $('#tudien-list').DataTable();
  } );
</script>
</body>
</html>

tạo app/Views/td_lists.php

 
      
   
   Từ điển - Lists
   
 
 
              Add Từ điển         Từ điểnn Lists         Từ điểnn List     
                                                               
                                          
                             Edit               Delete                          
                                      
 
     $(document).ready( function () {       $('#tudien-list').DataTable();   } ); 
 
 

tạo app/Views/td_edit.php

<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  
  <title>Từ điển - Edit</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
  
</head>

<body>
  <div class="container mt-5">
    <form method="post" id="update_td" name="update_td" 
    action="<?= site_url('/update') ?>">
      <input type="hidden" name="td_id" id="td_id" value="<?php echo $td_obj['td_id']; ?>">

      <div class="form-group">
        <label>Tiếng SlovakSlovak</label>
        <input type="text" name="td_ts" class="form-control" value="<?php echo $td_obj['td_ts']; ?>">
      </div>

      <div class="form-group">
        <label>Tiếng việtt</label>
        <!-- <input type="text" name="td_tv" class="form-control" value="<?php echo $td_obj['td_tv']; ?>"> -->

        <textarea rows="10" name="td_tv" class="form-control" value="<?php echo $td_obj['td_tv']; ?>"><?php echo $td_obj['td_tv']; ?></textarea>
      </div>

      <div class="form-group">
        <button type="submit" class="btn btn-primary btn-block">Save Data</button>
      </div>
    </form>
  </div>

  <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/jquery.validate.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/additional-methods.min.js"></script>
  <!-- <script>
    if ($("#update_td").length > 0) {
      $("#update_td").validate({
        rules: {
          name: {
            required: true,
          },
          email: {
            required: true,
            maxlength: 60,
            email: true,
          },
        },
        messages: {
          name: {
            required: "Name is required.",
          },
          email: {
            required: "Email is required.",
            email: "It does not seem to be a valid email.",
            maxlength: "The email should be or equal to 60 chars.",
          },
        },
      })
    }
  </script> -->
</body>

</html>

Xong.