CRUD là từ viết tắt của 4 thao tác cơ bản: Tạo, Đọc, Cập nhật, Xóa. Hầu hết các ứng dụng đều có một số loại chức năng CRUD và chúng ta có thể giả định rằng mọi lập trình viên đều phải xử lý CRUD tại một số thời điểm.
Điều kiện tiên quyết
- Chúng ta có một IDE như Visual Studio Code
- Cài Composer
- Có kiến thức cơ bản về CodeIgniter
Đầu tiên chúng ta cần thiết lập CodeIgniter. Để làm được điều đó, chúng tôi sẽ tạo một dự án có tên là CodeIgniter-crud. Từ command prompt, thực hiện lệnh sau:
composer create-project codeigniter4/appstarter CodeIgniter-crud
Tiếp theo, mở ứng dụng XAMPP và khởi động máy chủ Apache và MySQL của bạn như hình dưới đây:
Sau khi PHPMyAdmin khởi động, hãy nhấp vào nút ‘New’ trên thanh bên trái để tạo cơ sở dữ liệu mới. Nhập tên cơ sở dữ liệu ưa thích của bạn ở đây, chúng tôi đang sử dụng Codeigniter-crud làm tên cơ sở dữ liệu và nhấp vào nút create.
Bây giờ chúng ta sẽ thực hiện truy vấn SQL trong PHPMyadmin để tạo các bảng của chúng ta.
CREATE TABLE names (
id int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
name varchar(100) NOT NULL COMMENT 'Name',
email varchar(255) NOT NULL COMMENT 'Email Address',
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='datatable demo table' AUTO_INCREMENT=1;
INSERT INTO `names` (`id`, `name`, `email`) VALUES
(1, 'Gopal', 'gopal@gmail.com'),
(2, 'ram', 'vanya@gmail.com'),
(3, 'shyam', 'shyam@gmail.com'),
(4, 'gyan', 'gyan@gmail.com'),
(5, 'dhyan', 'dhyan@gmail.com'),
(6, 'geeta', 'geeta@gmail.com'),
(7, 'seeta', 'seeta@gmail.com');
Sau khi hoàn tất, hãy chuyển đến cmd và cd vào thư mục CodeIgniter-crud.
cd CodeIgniter-crud
Bây giờ, chạy câu lệnh cd CodeIgniter-crud && code để di chuyển vào thư mục và mở thư mục dự án trong VSCode.
Tiếp theo, mở tệp CodeIgniter-crud\app\Config\Database.php trong VSCode và sửa đổi thông tin đăng nhập cơ sở dữ liệu như sau:
pConnect' => false,
'DBDebug' => (ENVIRONMENT !== 'production'),
'cacheOn' => false,
'cacheDir' => '',
'charset' => 'utf8',
'DBCollat' => 'utf8_general_ci',
'swapPre' => '',
'encrypt' => false,
'compress' => false,
'strictOn' => false,
'failover' => [],
'port' => 3306,
];
//--------------------------------------------------------------------
public function __construct()
{
parent::__construct();
// Ensure that we always set the database group to 'tests' if
// we are currently running an automated test suite, so that
// we don't overwrite live data on accident.
if (ENVIRONMENT === 'testing')
{
$this->defaultGroup = 'tests';
// Under Travis-CI, we can set an ENV var named 'DB_GROUP'
// so that we can test against multiple databases.
if ($group = getenv('DB'))
{
if (is_file(TESTPATH . 'travis/Database.php'))
{
require TESTPATH . 'travis/Database.php';
if (! empty($dbconfig) && array_key_exists($group, $dbconfig))
{
$this->tests = $dbconfig[$group];
}
}
}
}
}
//--------------------------------------------------------------------
}
Tạo và thiết lập NamesCrud Controller
Tiếp theo, chúng ta sẽ tạo một controller để xử lý các hoạt động CRUD trong Ứng dụng CodeIgniter của chúng ta. Tạo một tệp có tên NamesCrud.php bên trong CodeIgniter-crud\app\Controllers với mã sau:
<?php
namespace App\Controllers;
use App\Models\NameModel;
use CodeIgniter\Controller;
class NamesCrud extends Controller
{
// show names list
public function index(){
$NameModel = new NameModel();
$data['users'] = $NameModel->orderBy('id', 'DESC')->findAll();
return view('namelist', $data);
}
// add name form
public function create(){
return view('addname');
}
// add data
public function store() {
$NameModel = new NameModel();
$data = [
'name' => $this->request->getVar('name'),
'email' => $this->request->getVar('email'),
];
$NameModel->insert($data);
return $this->response->redirect(site_url('/namelist'));
}
// show single name
public function singleUser($id = null){
$NameModel = new NameModel();
$data['user_obj'] = $NameModel->where('id', $id)->first();
return view('editnames', $data);
}
// update name data
public function update(){
$NameModel = new NameModel();
$id = $this->request->getVar('id');
$data = [
'name' => $this->request->getVar('name'),
'email' => $this->request->getVar('email'),
];
$NameModel->update($id, $data);
return $this->response->redirect(site_url('/namelist'));
}
// delete name
public function delete($id = null){
$NameModel = new NameModel();
$data['user'] = $NameModel->where('id', $id)->delete($id);
return $this->response->redirect(site_url('/namelist'));
}
}
Trong đoạn mã ở trên, lớp NamesCrud controller có các phương thức sau để thực hiện các hoạt động CRUD (xem, thêm, chỉnh sửa và xóa). Luồng của NamesCrud controller hoạt động như thế này:
- Hiển thị danh sách tên
- Một hàm để thêm tên
- Thêm chức năng để lưu trữ dữ liệu
- Thêm một hàm để hiển thị tên
- Thêm một chức năng để cập nhật dữ liệu tên
- Cuối cùng là chức năng xóa tên
Tạo và thiết lập NameModel Model
Lớp model cung cấp các phương thức để xử lý các hoạt động liên quan đến cơ sở dữ liệu, mở CodeIgniter-crud\app\Models\NameModel.php và thêm mã sau:
<?php
namespace App\Models;
use CodeIgniter\Model;
class NameModel extends Model
{
protected $table = 'names';
protected $primaryKey = 'id';
protected $allowedFields = ['name', 'email'];
}
Tạo các route cho ứng dụng
Bây giờ chúng ta sẽ tạo các route cho ứng dụng của mình để xử lý các hoạt động CRUD, vì vậy bạn cần thêm một số rule trong tệp CodeIgniter-crud\app\Config\Routes.php.
<?php namespace Config;
// Create a new instance of our RouteCollection class.
$routes = Services::routes();
// Load the system's routing file first, so that the app and ENVIRONMENT
// can override as needed.
if (file_exists(SYSTEMPATH . 'Config/Routes.php'))
{
require SYSTEMPATH . 'Config/Routes.php';
}
/**
* --------------------------------------------------------------------
* Router Setup
* --------------------------------------------------------------------
*/
$routes->setDefaultNamespace('App\Controllers');
$routes->setDefaultController('Home');
$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('/', 'Home::index');
// add these CRUD Routes
$routes->get('namelist', 'NamesCrud::index');
$routes->get('addname', 'NamesCrud::create');
$routes->post('submit-form', 'NamesCrud::store');
$routes->get('editnames/(:num)', 'NamesCrud::singleUser/$1');
$routes->post('update', 'NamesCrud::update');
$routes->get('delete/(:num)', 'NamesCrud::delete/$1');
/**
* --------------------------------------------------------------------
* Additional Routing
* --------------------------------------------------------------------
*
* There will often be times that you need additional routing and you
* need it to be able to override any defaults in this file. Environment
* based routes is one such time. require() additional route files here
* to make that happen.
*
* You will have access to the $routes object within that file without
* needing to reload it.
*/
if (file_exists(APPPATH . 'Config/' . ENVIRONMENT . '/Routes.php'))
{
require APPPATH . 'Config/' . ENVIRONMENT . '/Routes.php';
}
Tạo Views
Bây giờ cấu trúc ứng dụng của chúng ta đã hoàn tất, hãy làm cho ứng dụng hoạt động bằng cách hiển thị nó một cách trực quan. Để bắt đầu, trong CodeIgniter-crud\app\Views, hãy tạo các tệp sau:
- addname.php
- namelist.php
- editnames.php
Mở file namelist.php và thêm vào đoạn code sau:
<!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 Crud</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<div class="container mt-4">
<h1>Codeigniter Crud tutorial on code-source.tempurl.host</h1>
<div class="d-flex justify-content-end">
<a href="<?php echo site_url('/addname') ?>" class="btn btn-primary">Add a Name & email</a>
</div>
<?php
if(isset($_SESSION['msg'])){
echo $_SESSION['msg'];
}
?>
<div class="mt-3">
<table class="table table-bordered" id="users-list">
<thead>
<tr>
<th>User Id</th>
<th>Name</th>
<th>Email</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php if($users): ?>
<?php foreach($users as $user): ?>
<tr>
<td><?php echo $user['id']; ?></td>
<td><?php echo $user['name']; ?></td>
<td><?php echo $user['email']; ?></td>
<td>
<a href="<?php echo base_url('editnames/'.$user['id']);?>" class="btn btn-warning">Edit</a>
<a href="<?php echo base_url('delete/'.$user['id']);?>" class="btn btn-danger">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">
<script type="text/javascript" src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready( function () {
$('#users-list').DataTable();
} );
</script>
</body>
</html>
Ở đây chúng ta lấy dữ liệu từ cơ sở dữ liệu của mình, sử dụng bootstrap và Jquery datatable để hiển thị dữ liệu.
Tiếp theo, mở tệp CodeIgniter-crud\app\Views\addname.php và thêm đoạn mã sau vào đó.
<!DOCTYPE html>
<html>
<head>
<title>Codeigniter Crud</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<style>
.container {
max-width: 500px;
}
.error {
display: block;
padding-top: 5px;
font-size: 14px;
color: red;
}
</style>
</head>
<body>
<div class="container mt-5">
<form method="post" id="addname" name="addname"
action="<?= site_url('/submit-form') ?>">
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control">
</div>
<div class="form-group">
<label>Email</label>
<input type="text" name="email" class="form-control">
</div>
<div class="form-group">
<button type="submit" class="btn btn-success">Add Name & email</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>
Ở đây chúng ta đã thêm một form để lưu trữ dữ liệu trong cơ sở dữ liệu. Sau khi đã lưu dữ liệu ở addname.php, chúng ta cần cho phép người dùng chỉnh sửa tên. Để làm điều đó, hãy mở tệp editnames.php và nhập mã sau:
<!DOCTYPE html>
<html>
<head>
<title>Codeigniter Crud</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<style> .container {
max-width: 500px;
}
.error {
display: block;
padding-top: 5px;
font-size: 14px;
color: red;
}
</style>
</head>
<body>
<div class="container mt-5">
<h1>Codeigniter Crud tutorial on code-source.tempurl.host</h1>
<form method="post" id="update_user" name="update_user"
action="<?= site_url('/update') ?>">
<input type="hidden" name="id" id="id" value="<?php echo $user_obj['id']; ?>">
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control" value="<?php echo $user_obj['name']; ?>">
</div>
<div class="form-group">
<label>Email</label>
<input type="email" name="email" class="form-control" value="<?php echo $user_obj['email']; ?>">
</div>
<div class="form-group">
<button type="submit" class="btn btn-warning">Edit 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_user").length > 0) {
$("#update_user").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>
Sau khi hoàn tất, hãy chạy lệnh php spark serve trong cmd của bạn, sau đó truy cập http://localhost:8080/index.php/namelist trong trình duyệt của bạn để xem thứ gì đó tương tự như thế này.