'ID', 'name' => 'Họ và tên', 'email' => 'Email', 'birthday' => 'Ngày sinh', ]; $allowedDirections = ['ASC', 'DESC']; $sortBy = strtolower(trim((string)($_GET['sort'] ?? 'name'))); if (!array_key_exists($sortBy, $allowedColumns)) { $sortBy = 'name'; } $sortDir = strtoupper(trim((string)($_GET['dir'] ?? 'ASC'))); if (!in_array($sortDir, $allowedDirections, true)) { $sortDir = 'ASC'; } $keyword = trim((string)($_GET['q'] ?? '')); try { $pdo = getPdoConnection(true); ensureLab04StudentsTable($pdo, false); if ($keyword !== '') { $sql = "SELECT id, name, email, phone, birthday, created_at FROM students WHERE name LIKE :kw1 OR email LIKE :kw2 ORDER BY `{$sortBy}` {$sortDir}"; $stmt = $pdo->prepare($sql); $stmt->execute([ ':kw1' => '%' . $keyword . '%', ':kw2' => '%' . $keyword . '%', ]); } else { $sql = "SELECT id, name, email, phone, birthday, created_at FROM students ORDER BY `{$sortBy}` {$sortDir}"; $stmt = $pdo->prepare($sql); $stmt->execute(); } $students = $stmt->fetchAll(); } catch (Throwable $e) { $connectionError = $e; } function buildSortLink(string $col, string $currentSort, string $currentDir, string $keyword): string { $nextDir = ($currentSort === $col && $currentDir === 'ASC') ? 'DESC' : 'ASC'; $params = ['sort' => $col, 'dir' => $nextDir]; if ($keyword !== '') { $params['q'] = $keyword; } return 'sort_students.php?' . http_build_query($params); } function renderSortIndicator(string $col, string $currentSort, string $currentDir): string { if ($currentSort !== $col) { return '⇅'; } return $currentDir === 'ASC' ? '↑ ASC' : '↓ DESC'; } ?> Bài 11 - Sắp xếp danh sách sinh viên (ORDER BY name / email)

Bài 11: Sắp xếp danh sách sinh viên (sort_students.php)

Đang sắp xếp theo: () — Chiều:
Mặc định
ID Họ và tên Email Số điện thoại Ngày sinh
Không tìm thấy sinh viên nào.
#