Dự án tổng hợp loạt PHP và MySQL: gom các bài trước thành ứng dụng quản lý sinh viên hoàn chỉnh, viết bằng PDO, tổ chức thành lớp Repository, có đăng nhập, CRUD, tìm kiếm, phân trang, giao diện Bootstrap và xuất CSV.
- Tổ chức mã: cấu hình, kết nối, repository, các trang
- Dùng PDO với lớp SinhVienRepository
- Ghép đủ chức năng CRUD, tìm kiếm, phân trang, đăng nhập
- Kiểm tra bảo mật trước khi bàn giao
Một số khái niệm
Thay vì viết SQL rải rác trong từng trang, gom mọi truy vấn của một bảng vào một lớp Repository. Các trang chỉ gọi $repo->timKiem(...), $repo->them(...). Lợi ích: một chỗ sửa SQL, dễ kiểm thử, là bước đệm sang MVC (loạt PHP, Bài 17) và Laravel (Bài 19).
Cấu trúc
qlsv-pdo/
├── config.php # thông tin CSDL (không commit)
├── bootstrap.php # session, kết nối PDO, hàm e(), csrf(), yeu_cau_dang_nhap()
├── SinhVienRepository.php
├── dang-nhap.php, dang-xuat.php
├── index.php # danh sách + tìm kiếm + phân trang
├── form.php # thêm và sửa dùng chung
├── xoa.php, xuat-csv.php
└── partials/header.php, footer.php # Bootstrap 5 từ CDNbootstrap.php
<?php
declare(strict_types=1);
session_start();
$cfg = require __DIR__ . "/config.php";
$pdo = new PDO("mysql:host={$cfg['host']};dbname={$cfg['db']};charset=utf8mb4", $cfg["user"], $cfg["pass"], [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
]);
function e(?string $s): string { return htmlspecialchars($s ?? "", ENT_QUOTES, "UTF-8"); }
function csrf(): string { return $_SESSION["csrf"] ??= bin2hex(random_bytes(16)); }
function kiem_tra_csrf(): void {
if (!hash_equals(csrf(), $_POST["csrf"] ?? "")) { http_response_code(403); exit("CSRF"); }
}
function yeu_cau_dang_nhap(): void {
if (empty($_SESSION["user"])) { header("Location: dang-nhap.php"); exit; }
}
require __DIR__ . "/SinhVienRepository.php";
$repo = new SinhVienRepository($pdo);SinhVienRepository.php
<?php
final class SinhVienRepository {
public function __construct(private PDO $pdo) {}
public function timKiem(string $q, int $page, int $limit = 10): array {
$off = ($page - 1) * $limit;
$st = $this->pdo->prepare("SELECT SQL_CALC_FOUND_ROWS sv.*, l.ten_lop FROM sinhvien sv
LEFT JOIN lop l ON l.id = sv.lop_id
WHERE sv.ho_ten LIKE :q OR sv.ma_sv LIKE :q
ORDER BY sv.ho_ten LIMIT :lim OFFSET :off");
$st->bindValue(":q", "%$q%");
$st->bindValue(":lim", $limit, PDO::PARAM_INT);
$st->bindValue(":off", $off, PDO::PARAM_INT);
$st->execute();
$ds = $st->fetchAll();
$tong = (int)$this->pdo->query("SELECT FOUND_ROWS()")->fetchColumn();
return [$ds, $tong];
}
public function tim(int $id): ?array {
$st = $this->pdo->prepare("SELECT * FROM sinhvien WHERE id = ?");
$st->execute([$id]);
return $st->fetch() ?: null;
}
public function luu(array $d, ?int $id = null): int {
$cot = [$d["ma_sv"], $d["ho_ten"], $d["ngay_sinh"] ?: null, $d["email"] ?: null, (int)$d["lop_id"]];
if ($id) {
$this->pdo->prepare("UPDATE sinhvien SET ma_sv=?, ho_ten=?, ngay_sinh=?, email=?, lop_id=? WHERE id=?")
->execute([...$cot, $id]);
return $id;
}
$this->pdo->prepare("INSERT INTO sinhvien (ma_sv, ho_ten, ngay_sinh, email, lop_id) VALUES (?,?,?,?,?)")
->execute($cot);
return (int)$this->pdo->lastInsertId();
}
public function xoa(int $id): bool {
$st = $this->pdo->prepare("DELETE FROM sinhvien WHERE id = ?");
$st->execute([$id]);
return $st->rowCount() > 0;
}
public function kiemTra(array $d): array {
$loi = [];
if (!preg_match('/^SV\d{3,8}$/', $d["ma_sv"] ?? "")) $loi["ma_sv"] = "Mã dạng SV + số";
if (mb_strlen(trim($d["ho_ten"] ?? "")) < 3) $loi["ho_ten"] = "Họ tên tối thiểu 3 ký tự";
if (!empty($d["email"]) && !filter_var($d["email"], FILTER_VALIDATE_EMAIL)) $loi["email"] = "Email sai";
return $loi;
}
}index.php
<?php
require __DIR__ . "/bootstrap.php";
yeu_cau_dang_nhap();
$q = trim($_GET["q"] ?? ""); $page = max(1, (int)($_GET["page"] ?? 1));
[$ds, $tong] = $repo->timKiem($q, $page);
$so_trang = max(1, (int)ceil($tong / 10));
include __DIR__ . "/partials/header.php";
?>
<form class="d-flex gap-2 mb-3"><input class="form-control" name="q" value="<?= e($q) ?>" placeholder="Tìm tên hoặc mã">
<button class="btn btn-success">Tìm</button><a class="btn btn-primary" href="/form.php">+ Thêm</a>
<a class="btn btn-outline-secondary" href="/xuat-csv.php">Xuất CSV</a></form>
<table class="table table-striped">
<tr><th>Mã</th><th>Họ tên</th><th>Lớp</th><th></th></tr>
<?php foreach ($ds as $sv): ?>
<tr><td><?= e($sv["ma_sv"]) ?></td><td><?= e($sv["ho_ten"]) ?></td><td><?= e($sv["ten_lop"]) ?></td>
<td><a class="btn btn-sm btn-outline-primary" href="/form.php?id=<?= $sv["id"] ?>">Sửa</a>
<form method="post" action="xoa.php" class="d-inline" onsubmit="return confirm('Xóa?')">
<input type="hidden" name="csrf" value="<?= csrf() ?>"><input type="hidden" name="id" value="<?= $sv["id"] ?>">
<button class="btn btn-sm btn-outline-danger">Xóa</button></form></td></tr>
<?php endforeach; ?>
</table>
<nav><ul class="pagination">
<?php for ($i = 1; $i <= $so_trang; $i++): ?>
<li class="page-item <?= $i === $page ? "active" : "" ?>"><a class="page-link" href="/?<?= e(http_build_query(["q" => $q, "page" => $i])) ?>"><?= $i ?></a></li>
<?php endfor; ?>
</ul></nav>
<?php include __DIR__ . "/partials/footer.php"; ?>form.php dùng chung cho thêm và sửa: có ?id= thì nạp dữ liệu cũ; khi POST gọi $repo->kiemTra() rồi $repo->luu($_POST, $id). xuat-csv.php dùng fputcsv như loạt PHP, Bài 20.
Danh sách kiểm tra
- 100% truy vấn qua prepared statement (PDO).
- Mọi đầu ra qua e(); form POST có csrf().
- Mật khẩu người dùng: password_hash / password_verify.
- Trang quản trị gọi yeu_cau_dang_nhap().
- Lỗi CSDL ghi log, người dùng thấy thông báo chung.
- Có tệp database/qlsv.sql và README hướng dẫn cài.
Khi đã quen Repository, bạn sẽ thấy Eloquent của Laravel (loạt PHP, Bài 19) làm đúng việc này nhưng tự động hơn nhiều.
SQL_CALC_FOUND_ROWS đã bị đánh dấu lỗi thời trên MySQL 8; trên MySQL 8 hãy dùng một truy vấn COUNT(*) riêng như Bài 4.
- Hoàn thiện ứng dụng theo cấu trúc trên, chạy đủ CRUD.
- Thêm repository cho bảng lop và trang quản lý lớp.
- Thêm trang nhập điểm và bảng điểm có điểm trung bình tín chỉ.
- Đưa ứng dụng lên hosting miễn phí và nộp đường dẫn.
- Gom SQL vào Repository; trang chỉ gọi phương thức.
- PDO + bindValue PARAM_INT cho LIMIT/OFFSET.
- Ghép CRUD, tìm kiếm, phân trang, đăng nhập, CSRF, CSV.
- Là cầu nối sang MVC và Laravel.

