NenTang.vn
Thiết kế Lập trình Web BackendLập trình căn bản PHP
Tạo chức năng CRUD (Xem-Read, Thêm-Create, Sửa-Edit, Xóa-Delete) cho danh mục Phẳng - Edit
Chương 10 · Bài 6
Dự án thực tế mẫu (PHP thuần) - Trang web bán hàng trực tuyến - Thiết kế Backend
Thời lượng: 114 phútĐọc khoảng: 6 phút
Danh mục hình và bảng
Từ viết tắt
Nội dung bài học không khai báo từ viết tắt bằng thẻ abbr.
Nội dung bài học
Workflow
Step 1: tạo chức năng edit dùng để hiển thị Form với dữ liệu cũ cho người dùng cập nhật
- Tạo file
/backend/functions/loaisanpham/edit.phpđể hiển thị form cho người dùng nhập liệu và xử lý UPDATE vào database - Nội dung file:
php
1<!-- Nhúng file cấu hình để xác định được Tên và Tiêu đề của trang hiện tại người dùng đang truy cập -->2<?php include_once(__DIR__ . '/../../layouts/config.php'); ?>3 4<!DOCTYPE html>5<html>6 7<head>8 <!-- Nhúng file quản lý phần HEAD -->9 <?php include_once(__DIR__ . '/../../layouts/head.php'); ?>10</head>11 12<body class="d-flex flex-column h-100">13 <!-- header -->14 <?php include_once(__DIR__ . '/../../layouts/partials/header.php'); ?>15 <!-- end header -->16 17 <div class="container-fluid">18 <div class="row">19 <!-- sidebar -->20 <?php include_once(__DIR__ . '/../../layouts/partials/sidebar.php'); ?>21 <!-- end sidebar -->22 23 <main role="main" class="col-md-10 ml-sm-auto px-4 mb-2">24 <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">25 <h1 class="h2">Hiệu chỉnh Loại sản phẩm</h1>26 </div>27 28 <!-- Block content -->29 <?php30 // Hiển thị tất cả lỗi trong PHP31 // Chỉ nên hiển thị lỗi khi đang trong môi trường Phát triển (Development)32 // Không nên hiển thị lỗi trên môi trường Triển khai (Production)33 ini_set('display_errors', 1);34 ini_set('display_startup_errors', 1);35 error_reporting(E_ALL);36 37 // Truy vấn database38 // 1. Include file cấu hình kết nối đến database, khởi tạo kết nối $conn39 include_once(__DIR__ . '/../../../dbconnect.php');40 41 /* --- 42 --- 2. Truy vấn dữ liệu Loại Sản phẩm theo khóa chính43 --- 44 */45 // Chuẩn bị câu truy vấn $sqlSelect, lấy dữ liệu ban đầu của record cần update46 // Lấy giá trị khóa chính được truyền theo dạng QueryString Parameter key1=value1&key2=value2...47 $lsp_ma = $_GET['lsp_ma'];48 $sqlSelect = "SELECT * FROM `loaisanpham` WHERE lsp_ma=$lsp_ma;";49 50 // Thực thi câu truy vấn SQL để lấy về dữ liệu ban đầu của record cần update51 $resultSelect = mysqli_query($conn, $sqlSelect);52 $loaisanphamRow = mysqli_fetch_array($resultSelect, MYSQLI_ASSOC); // 1 record53 /* --- End Truy vấn dữ liệu Sản phẩm theo khóa chính --- */54 ?>55 56 <!-- Block content -->57 <form name="frmLoaiSanPham" id="frmLoaiSanPham" method="post" action="">58 <div class="form-group">59 <label for="lsp_ma">Mã loại sản phẩm</label>60 <input type="text" class="form-control" id="lsp_ma" name="lsp_ma" placeholder="Mã loại sản phẩm" value="<?= $loaisanphamRow['lsp_ma'] ?>" readonly>61 <small id="idHelp" class="form-text text-muted">Mã loại sản phẩm không được hiệu chỉnh.</small>62 </div>63 <div class="form-group">64 <label for="lsp_ten">Tên loại sản phẩm</label>65 <input type="text" class="form-control" id="lsp_ten" name="lsp_ten" placeholder="Tên loại sản phẩm" value="<?= $loaisanphamRow['lsp_ten'] ?>">66 </div>67 <div class="form-group">68 <label for="lsp_mota">Mô tả loại sản phẩm</label>69 <textarea class="form-control" id="lsp_mota" name="lsp_mota" placeholder="Mô tả loại sản phẩm"><?= $loaisanphamRow['lsp_mota'] ?></textarea>70 </div>71 <button class="btn btn-primary" name="btnSave">Lưu dữ liệu</button>72 </form>73 74 <?php75 // 2. Nếu người dùng có bấm nút "Lưu dữ liệu"76 if (isset($_POST['btnSave'])) {77 // Lấy dữ liệu người dùng hiệu chỉnh gởi từ REQUEST POST78 $lsp_ten = $_POST['lsp_ten'];79 $lsp_mota = $_POST['lsp_mota'];80 81 // Kiểm tra ràng buộc dữ liệu (Validation)82 // Tạo biến lỗi để chứa thông báo lỗi83 $errors = [];84 85 // Validate Tên loại Sản phẩm86 // required87 if (empty($lsp_ten)) {88 $errors['lsp_ten'][] = [89 'rule' => 'required',90 'rule_value' => true,91 'value' => $lsp_ten,92 'msg' => 'Vui lòng nhập tên Loại sản phẩm'93 ];94 }95 // minlength 396 if (!empty($lsp_ten) && strlen($lsp_ten) < 3) {97 $errors['lsp_ten'][] = [98 'rule' => 'minlength',99 'rule_value' => 3,100 'value' => $lsp_ten,101 'msg' => 'Tên Loại sản phẩm phải có ít nhất 3 ký tự'102 ];103 }104 // maxlength 50105 if (!empty($lsp_ten) && strlen($lsp_ten) > 50) {106 $errors['lsp_ten'][] = [107 'rule' => 'maxlength',108 'rule_value' => 50,109 'value' => $lsp_ten,110 'msg' => 'Tên Loại sản phẩm không được vượt quá 50 ký tự'111 ];112 }113 114 // Validate Diễn giải115 // required116 if (empty($lsp_mota)) {117 $errors['lsp_mota'][] = [118 'rule' => 'required',119 'rule_value' => true,120 'value' => $lsp_mota,121 'msg' => 'Vui lòng nhập mô tả Loại sản phẩm'122 ];123 }124 // minlength 3125 if (!empty($lsp_mota) && strlen($lsp_mota) < 3) {126 $errors['lsp_mota'][] = [127 'rule' => 'minlength',128 'rule_value' => 3,129 'value' => $lsp_mota,130 'msg' => 'Mô tả loại sản phẩm phải có ít nhất 3 ký tự'131 ];132 }133 // maxlength 255134 if (!empty($lsp_mota) && strlen($lsp_mota) > 255) {135 $errors['lsp_mota'][] = [136 'rule' => 'maxlength',137 'rule_value' => 255,138 'value' => $lsp_mota,139 'msg' => 'Mô tả loại sản phẩm không được vượt quá 255 ký tự'140 ];141 }142 }143 ?>144 145 <!-- Nếu có lỗi VALIDATE dữ liệu thì hiển thị ra màn hình 146 - Sử dụng thành phần (component) Alert của Bootstrap147 - Mỗi một lỗi hiển thị sẽ in theo cấu trúc Danh sách không thứ tự UL > LI148 -->149 <?php if (150 isset($_POST['btnSave']) // Nếu người dùng có bấm nút "Lưu dữ liệu"151 && isset($errors) // Nếu biến $errors có tồn tại152 && (!empty($errors)) // Nếu giá trị của biến $errors không rỗng153 ) : ?>154 <div id="errors-container" class="alert alert-danger face my-2" role="alert">155 <button type="button" class="close" data-dismiss="alert" aria-label="Close">156 <span aria-hidden="true">×</span>157 </button>158 <ul>159 <?php foreach ($errors as $fields) : ?>160 <?php foreach ($fields as $field) : ?>161 <li><?php echo $field['msg']; ?></li>162 <?php endforeach; ?>163 <?php endforeach; ?>164 </ul>165 </div>166 <?php endif; ?>167 168 <?php169 // Nếu không có lỗi VALIDATE dữ liệu (tức là dữ liệu đã hợp lệ)170 // Tiến hành thực thi câu lệnh SQL Query Database171 // => giá trị của biến $errors là rỗng172 if (173 isset($_POST['btnSave']) // Nếu người dùng có bấm nút "Lưu dữ liệu"174 && (!isset($errors) || (empty($errors))) // Nếu biến $errors không tồn tại Hoặc giá trị của biến $errors rỗng175 ) {176 // VALIDATE dữ liệu đã hợp lệ177 // Thực thi câu lệnh SQL QUERY178 // Câu lệnh UPDATE179 $sql = "UPDATE `loaisanpham` SET lsp_ten = '$lsp_ten', lsp_mota = '$lsp_mota' WHERE lsp_ma = $lsp_ma;";180 181 // Thực thi INSERT182 mysqli_query($conn, $sql) or die("<b>Có lỗi khi thực thi câu lệnh SQL: </b>" . mysqli_error($conn) . "<br /><b>Câu lệnh vừa thực thi:</b></br>$sql");183 184 // Đóng kết nối185 mysqli_close($conn);186 187 // Sau khi cập nhật dữ liệu, tự động điều hướng về trang Danh sách188 // Điều hướng bằng Javascript189 echo '<script>location.href = "index.php";</script>';190 }191 ?>192 <!-- End block content -->193 </main>194 </div>195 </div>196 197 <!-- footer -->198 <?php include_once(__DIR__ . '/../../layouts/partials/footer.php'); ?>199 <!-- end footer -->200 201 <!-- Nhúng file quản lý phần SCRIPT JAVASCRIPT -->202 <?php include_once(__DIR__ . '/../../layouts/scripts.php'); ?>203 204 <!-- Các file Javascript sử dụng riêng cho trang này, liên kết tại đây -->205 <!-- <script src="..."></script> -->206 <script>207 $(document).ready(function() {208 $("#frmLoaiSanPham").validate({209 rules: {210 lsp_ten: {211 required: true,212 minlength: 3,213 maxlength: 50214 },215 lsp_mota: {216 required: true,217 minlength: 3,218 maxlength: 255219 }220 },221 messages: {222 lsp_ten: {223 required: "Vui lòng nhập tên Loại sản phẩm",224 minlength: "Tên Loại sản phẩm phải có ít nhất 3 ký tự",225 maxlength: "Tên Loại sản phẩm không được vượt quá 50 ký tự"226 },227 lsp_mota: {228 required: "Vui lòng nhập mô tả cho Loại sản phẩm",229 minlength: "Mô tả cho Loại sản phẩm phải có ít nhất 3 ký tự",230 maxlength: "Mô tả cho Loại sản phẩm không được vượt quá 255 ký tự"231 },232 },233 errorElement: "em",234 errorPlacement: function(error, element) {235 // Thêm class `invalid-feedback` cho field đang có lỗi236 error.addClass("invalid-feedback");237 if (element.prop("type") === "checkbox") {238 error.insertAfter(element.parent("label"));239 } else {240 error.insertAfter(element);241 }242 },243 success: function(label, element) {},244 highlight: function(element, errorClass, validClass) {245 $(element).addClass("is-invalid").removeClass("is-valid");246 },247 unhighlight: function(element, errorClass, validClass) {248 $(element).addClass("is-valid").removeClass("is-invalid");249 }250 });251 });252 </script>253</body>254 255</html>
