prepare("SELECT MAX(subject_id) as max_id FROM subjects"); $stmt->execute(); $result = $stmt->fetch(PDO::FETCH_ASSOC); $next_id = ($result['max_id'] ?? 0) + 1; // Insert the new subject $stmt = $DBcon->prepare("INSERT INTO subjects (subject_id, subjectname, subjectclass, section) VALUES (?, ?, ?, ?)"); $success = $stmt->execute([$next_id, $subjectname, $subjectclass, $section]); if ($success) { header("Location: subjects.php?message=Subject added successfully&type=success"); } else { header("Location: subjects.php?action=add&message=Failed to add subject&type=danger"); } } catch(PDOException $e) { header("Location: subjects.php?action=add&message=Database error: " . urlencode($e->getMessage()) . "&type=danger"); } } function updateSubject() { global $DBcon; if ($_SERVER['REQUEST_METHOD'] !== 'POST') { header("Location: subjects.php?message=Invalid request&type=danger"); exit(); } $subject_id = sanitize_input($_POST['subject_id'] ?? ''); $subjectname = sanitize_input($_POST['subjectname'] ?? ''); $subjectclass = sanitize_input($_POST['subjectclass'] ?? ''); $section = sanitize_input($_POST['section'] ?? ''); // Validate required fields if (empty($subject_id) || empty($subjectname) || empty($subjectclass) || empty($section)) { header("Location: subjects.php?action=edit&id=$subject_id&message=All fields are required&type=danger"); exit(); } try { $stmt = $DBcon->prepare("UPDATE subjects SET subjectname = ?, subjectclass = ?, section = ? WHERE subject_id = ?"); $success = $stmt->execute([$subjectname, $subjectclass, $section, $subject_id]); if ($success) { header("Location: subjects.php?message=Subject updated successfully&type=success"); } else { header("Location: subjects.php?action=edit&id=$subject_id&message=Failed to update subject&type=danger"); } } catch(PDOException $e) { header("Location: subjects.php?action=edit&id=$subject_id&message=Database error: " . urlencode($e->getMessage()) . "&type=danger"); } } function deleteSubject() { global $DBcon; $subject_id = $_GET['id'] ?? ''; if (empty($subject_id)) { header("Location: subjects.php?message=Subject ID is required&type=danger"); exit(); } try { $stmt = $DBcon->prepare("DELETE FROM subjects WHERE subject_id = ?"); $success = $stmt->execute([$subject_id]); if ($success) { header("Location: subjects.php?message=Subject deleted successfully&type=success"); } else { header("Location: subjects.php?message=Failed to delete subject&type=danger"); } } catch(PDOException $e) { header("Location: subjects.php?message=Database error: " . urlencode($e->getMessage()) . "&type=danger"); } } ?>