0) { $message = 'Student ID already exists.'; $message_type = 'danger'; } else { $qr = 'STU_' . $sid . '_' . uniqid(); $sql = "INSERT INTO students (student_id, qr_code, full_name, gender_id, year_level, course_id, department_id, school_id, birth_date, contact_number, email, address, created_at, updated_at, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW(), ?)"; $stmt = mysqli_prepare($conn, $sql); // null-safe birth_date $bd = $birth_date ?: null; mysqli_stmt_bind_param($stmt, 'sssiiiiissssi', $sid, $qr, $full, $gender_id, $year_level, $course_id, $department_id, $school_id, $bd, $contact, $email, $address, $status); if (mysqli_stmt_execute($stmt)) { $_SESSION['flash_message'] = 'Student added successfully!'; $_SESSION['flash_type'] = 'success'; header('Location: manage_students.php'); exit(); } else { $message = 'Error adding student: ' . mysqli_error($conn); $message_type = 'danger'; } mysqli_stmt_close($stmt); } mysqli_stmt_close($dup); } } // --- Update Student (Modal) --- elseif (isset($_POST['modal_update_student'])) { $id = intval($_POST['id'] ?? 0); $sid = trim($_POST['student_id'] ?? ''); $full = trim($_POST['full_name'] ?? ''); $gender_id = intval($_POST['gender_id'] ?? 0); $year_level = intval($_POST['year_level'] ?? 0); $course_id = intval($_POST['course_id'] ?? 0); $department_id = intval($_POST['department_id'] ?? 0); $school_id = intval($_POST['school_id'] ?? 0); $birth_date = ($_POST['birth_date'] ?? '') ?: null; if ($birth_date === '0000-00-00') { $birth_date = null; } $contact = trim($_POST['contact_number'] ?? ''); $email = trim($_POST['email'] ?? ''); $address = trim($_POST['address'] ?? ''); $status = isset($_POST['status']) ? 1 : 0; if ($id <= 0) { $message = 'Invalid student id.'; $message_type = 'danger'; } elseif ($sid === '' || $full === '' || $gender_id === 0 || $year_level === 0 || $course_id === 0 || $department_id === 0 || $school_id === 0) { $message = 'Please fill in all required fields.'; $message_type = 'danger'; } else { // duplicate student_id check excluding current id $dup = mysqli_prepare($conn, "SELECT id FROM students WHERE student_id = ? AND id != ?"); mysqli_stmt_bind_param($dup, 'si', $sid, $id); mysqli_stmt_execute($dup); mysqli_stmt_store_result($dup); if (mysqli_stmt_num_rows($dup) > 0) { $message = 'Student ID already exists.'; $message_type = 'danger'; } else { // Build dynamic update allowing NULLs $set = 'student_id = ?, full_name = ?, gender_id = ?, year_level = ?, course_id = ?, department_id = ?, school_id = ?, status = ?, updated_at = NOW()'; $types = 'ssiiiiii'; $params = [$sid, $full, $gender_id, $year_level, $course_id, $department_id, $school_id, $status]; if ($birth_date) { $set .= ', birth_date = ?'; $types .= 's'; $params[] = $birth_date; } else { $set .= ', birth_date = NULL'; } if ($contact !== '') { $set .= ', contact_number = ?'; $types .= 's'; $params[] = $contact; } else { $set .= ', contact_number = NULL'; } if ($email !== '') { $set .= ', email = ?'; $types .= 's'; $params[] = $email; } else { $set .= ', email = NULL'; } if ($address !== '') { $set .= ', address = ?'; $types .= 's'; $params[] = $address; } else { $set .= ', address = NULL'; } $sql = "UPDATE students SET $set WHERE id = ?"; $types .= 'i'; $params[] = $id; $stmt = mysqli_prepare($conn, $sql); if ($stmt && mysqli_stmt_bind_param($stmt, $types, ...$params) && mysqli_stmt_execute($stmt)) { $_SESSION['flash_message'] = 'Student updated successfully!'; $_SESSION['flash_type'] = 'success'; header('Location: manage_students.php'); exit(); } else { $message = 'Error updating student: ' . mysqli_error($conn); $message_type = 'danger'; } if ($stmt) { mysqli_stmt_close($stmt); } } mysqli_stmt_close($dup); } } // --- Delete Student --- if (isset($_POST['delete_student'])) { $student_id = isset($_POST['id']) ? intval($_POST['id']) : 0; if ($student_id > 0) { // Check if student exists $check_sql = "SELECT id, full_name FROM students WHERE id = ?"; $stmt = mysqli_prepare($conn, $check_sql); mysqli_stmt_bind_param($stmt, 'i', $student_id); mysqli_stmt_execute($stmt); $result = mysqli_stmt_get_result($stmt); if ($row = mysqli_fetch_assoc($result)) { $student_name = $row['full_name']; // Remove associated files before deletion $fetch_sql = "SELECT picture_path, qr_code_image, full_name FROM students WHERE id = ?"; $stmtf = mysqli_prepare($conn, $fetch_sql); mysqli_stmt_bind_param($stmtf, 'i', $student_id); mysqli_stmt_execute($stmtf); $resf = mysqli_stmt_get_result($stmtf); if ($fileRow = mysqli_fetch_assoc($resf)) { if (!empty($fileRow['picture_path']) && file_exists('../' . $fileRow['picture_path'])) { @unlink('../' . $fileRow['picture_path']); } if (!empty($fileRow['qr_code_image']) && file_exists('../' . $fileRow['qr_code_image'])) { @unlink('../' . $fileRow['qr_code_image']); } // Ensure we have name $student_name = $fileRow['full_name']; } mysqli_stmt_close($stmtf); // Delete the student; related attendance/logs cascade via FK constraints $sql = "DELETE FROM students WHERE id = ?"; $stmt3 = mysqli_prepare($conn, $sql); mysqli_stmt_bind_param($stmt3, 'i', $student_id); if (mysqli_stmt_execute($stmt3)) { $affected_rows = mysqli_stmt_affected_rows($stmt3); if ($affected_rows > 0) { $_SESSION['flash_message'] = "Student '$student_name' deleted successfully!"; $_SESSION['flash_type'] = 'success'; header("Location: manage_students.php?msg=deleted"); exit(); } else { $message = 'No student was deleted. Student might not exist or there was an error.'; $message_type = 'warning'; error_log("No rows affected when deleting student ID: $student_id"); } } else { $error = mysqli_error($conn); $message = 'Error deleting student: ' . $error; $message_type = 'danger'; error_log("SQL Error deleting student: $error"); } mysqli_stmt_close($stmt3); } else { $message = 'Student not found!'; $message_type = 'danger'; error_log("Student ID $student_id not found"); } mysqli_stmt_close($stmt); } } // --- Export to Excel --- elseif (isset($_POST['export_excel'])) { exportToExcel($conn); exit(); } // --- Bulk Actions --- elseif (isset($_POST['bulk_action']) && isset($_POST['selected_students'])) { $bulk_action = sanitizeInput($_POST['bulk_action']); $selected_students = $_POST['selected_students']; // Validate selected students if (empty($selected_students) || !is_array($selected_students)) { $message = 'No students selected.'; $message_type = 'warning'; } else { // Sanitize all IDs $sanitized_ids = array_map('intval', $selected_students); $ids = implode(',', $sanitized_ids); $count = count($sanitized_ids); // Check if force delete is requested $force_delete = isset($_POST['force_bulk_delete']) && $_POST['force_bulk_delete'] == 1; // Prepare SQL based on action if ($bulk_action === 'activate') { $sql = "UPDATE students SET status = 1, updated_at = NOW() WHERE id IN ($ids)"; $success_msg = "$count student(s) activated successfully!"; } elseif ($bulk_action === 'deactivate') { $sql = "UPDATE students SET status = 0, updated_at = NOW() WHERE id IN ($ids)"; $success_msg = "$count student(s) deactivated successfully!"; } elseif ($bulk_action === 'delete') { // Direct bulk delete; related attendance and logs cascade via FK constraints $sql = "DELETE FROM students WHERE id IN ($ids)"; $success_msg = "$count student(s) deleted successfully!"; } if (isset($sql) && empty($message)) { // If deleting, clean up files first if ($bulk_action === 'delete') { $files_sql = "SELECT id, picture_path, qr_code_image FROM students WHERE id IN ($ids)"; $files_result = mysqli_query($conn, $files_sql); if ($files_result) { while ($f = mysqli_fetch_assoc($files_result)) { if (!empty($f['picture_path']) && file_exists('../' . $f['picture_path'])) { @unlink('../' . $f['picture_path']); } if (!empty($f['qr_code_image']) && file_exists('../' . $f['qr_code_image'])) { @unlink('../' . $f['qr_code_image']); } } } } error_log("Executing SQL: $sql"); if (mysqli_query($conn, $sql)) { $affected_rows = mysqli_affected_rows($conn); error_log("Bulk action affected $affected_rows row(s)"); $_SESSION['flash_message'] = $success_msg; $_SESSION['flash_type'] = 'success'; header("Location: manage_students.php?msg=bulk"); exit(); } else { $error = mysqli_error($conn); $message = 'Error performing bulk action: ' . $error; $message_type = 'danger'; error_log("SQL Error in bulk action: $error"); } } } } } // Check for flash messages from session if (isset($_SESSION['flash_message'])) { $message = $_SESSION['flash_message']; $message_type = $_SESSION['flash_type']; unset($_SESSION['flash_message']); unset($_SESSION['flash_type']); } // ==================== GET STUDENTS DATA ==================== $students = []; $sql = "SELECT s.*, g.name as gender, c.code as course_code, c.name as course_name, d.code as department_code, d.name as department_name, sc.code as school_code, sc.name as school_name FROM students s LEFT JOIN genders g ON s.gender_id = g.id LEFT JOIN courses c ON s.course_id = c.id LEFT JOIN departments d ON s.department_id = d.id LEFT JOIN schools sc ON s.school_id = sc.id ORDER BY s.created_at DESC"; $result = mysqli_query($conn, $sql); if ($result) { while ($row = mysqli_fetch_assoc($result)) { $students[] = $row; } } else { error_log("Error fetching students: " . mysqli_error($conn)); } // Dropdown data for modals $genders = []; $courses = []; $departments = []; $schools = []; $r = mysqli_query($conn, "SELECT * FROM genders ORDER BY id"); if ($r) { while ($row = mysqli_fetch_assoc($r)) { $genders[] = $row; } } $r = mysqli_query($conn, "SELECT * FROM courses WHERE status = 1 ORDER BY code"); if ($r) { while ($row = mysqli_fetch_assoc($r)) { $courses[] = $row; } } $r = mysqli_query($conn, "SELECT * FROM departments WHERE status = 1 ORDER BY code"); if ($r) { while ($row = mysqli_fetch_assoc($r)) { $departments[] = $row; } } $r = mysqli_query($conn, "SELECT * FROM schools WHERE status = 1 ORDER BY code"); if ($r) { while ($row = mysqli_fetch_assoc($r)) { $schools[] = $row; } } // ==================== INCLUDE HEADER ==================== include '../includes/header.php'; ?>

Manage Students

Manage student records
PHP Version: | DB Connected:
Total

Active

Inactive

Departments

Student List
# Student ID Student Course Year Status Actions

No students found.

Add First Student
<?php echo htmlspecialchars($student['full_name']); ?>
Yr Active Inactive
$(document).ready(function() { // Initialize DataTable const table = $("#studentsTable").DataTable({ pageLength: 25, lengthMenu: [[15, 25, 50, 100, -1], [15, 25, 50, 100, "All"]], order: [[2, "asc"]], // Sort by Student ID responsive: true, columnDefs: [ { orderable: false, targets: [0, 1, 7] }, { searchable: false, targets: [0, 1, 5, 6, 7] }, { visible: false, targets: [0] } ], language: { search: "_INPUT_", searchPlaceholder: "Search...", lengthMenu: "Show _MENU_", info: "Showing _START_ to _END_ of _TOTAL_", infoEmpty: "No students", infoFiltered: "(filtered from _MAX_ total)" } }); // Open Add modal document.getElementById('openAddModal').addEventListener('click', function(){ const form = document.querySelector('#addStudentModal form'); form.reset(); const addModal = new bootstrap.Modal(document.getElementById('addStudentModal')); addModal.show(); }); // Open Edit modal and populate $(document).on('click', '.edit-student', function(){ const d = $(this).data(); $('#edit_id').val(d.id); $('#edit_student_id').val(d.student_id); $('#edit_full_name').val(d.full_name); $('#edit_gender_id').val(String(d.gender_id)); $('#edit_year_level').val(String(d.year_level)); $('#edit_course_id').val(String(d.course_id)); $('#edit_department_id').val(String(d.department_id)); $('#edit_school_id').val(String(d.school_id)); $('#edit_birth_date').val(d.birth_date && d.birth_date !== '0000-00-00' ? d.birth_date : ''); $('#edit_contact_number').val(d.contact_number || ''); $('#edit_email').val(d.email || ''); $('#edit_address').val(d.address || ''); $('#edit_status').prop('checked', Number(d.status) === 1); const editModal = new bootstrap.Modal(document.getElementById('editStudentModal')); editModal.show(); }); // Custom search $("#searchInput").on("keyup", function() { table.search($(this).val()).draw(); }); // Bulk selection functionality $("#toggleAll").change(function() { $(".student-check").prop("checked", this.checked); updateBulkSelection(); }); $(document).on("change", ".student-check", function() { if (!this.checked) { $("#toggleAll").prop("checked", false); } updateBulkSelection(); }); // Delete confirmation $(document).on("click", ".delete-student", function(e) { e.preventDefault(); const studentId = $(this).data("id"); const studentName = $(this).data("name"); // Create confirmation dialog const confirmed = confirm(`Are you sure you want to delete student "${studentName}"?\\nThis action cannot be undone.`); if (confirmed) { // Create and submit form const form = document.createElement("form"); form.method = "POST"; form.action = ""; const deleteInput = document.createElement("input"); deleteInput.type = "hidden"; deleteInput.name = "delete_student"; deleteInput.value = "1"; form.appendChild(deleteInput); const idInput = document.createElement("input"); idInput.type = "hidden"; idInput.name = "id"; idInput.value = studentId; form.appendChild(idInput); const csrfInput = document.createElement("input"); csrfInput.type = "hidden"; csrfInput.name = "csrf_token"; csrfInput.value = ""; form.appendChild(csrfInput); document.body.appendChild(form); form.submit(); } }); // Bulk form validation $("#bulkForm").submit(function(e) { const selectedCount = $(".student-check:checked").length; const action = $("select[name=\'bulk_action\']").val(); if (selectedCount === 0) { e.preventDefault(); alert("Please select at least one student."); return false; } if (!action) { e.preventDefault(); alert("Please select a bulk action."); return false; } if (action === "delete") { e.preventDefault(); if (confirm(`Delete ${selectedCount} student(s)?\\nThis action cannot be undone.`)) { return true; } return false; } return true; }); }); // Bulk selection functions function updateBulkSelection() { const selectedCount = $(".student-check:checked").length; $("#selectedCount").text(selectedCount); if (selectedCount > 0) { $(".bulk-actions-bar").show(); $("#studentsTable_wrapper .col-sm-12:first").css("margin-top", "50px"); } else { $(".bulk-actions-bar").hide(); $("#studentsTable_wrapper .col-sm-12:first").css("margin-top", "0"); } const totalCheckboxes = $(".student-check").length; $("#toggleAll").prop("checked", selectedCount === totalCheckboxes && totalCheckboxes > 0); } function clearBulkSelection() { $(".student-check").prop("checked", false); $("#toggleAll").prop("checked", false); updateBulkSelection(); } // Print Report function printReport() { const table = $("#studentsTable").DataTable(); const data = table.rows({ search: \'applied\' }).data().toArray(); if (data.length === 0) { alert("No data to print."); return; } const printWindow = window.open("", "_blank"); printWindow.document.write(` Student List - <?php echo date("Y-m-d"); ?>

Student List

Date:

Total: ${data.length} students

${data.map((row, index) => { const studentId = $(row[2]).find(".text-primary").text() || row[2]; const studentName = $(row[3]).find(".fw-bold").text() || row[3]; const course = $(row[4]).text(); const year = $(row[5]).text(); const status = $(row[6]).text(); return ` `; }).join("")}
# Student ID Name Course Year Status
${index + 1} ${studentId} ${studentName} ${course} ${year} ${status}
'; $page_scripts .= '\n