File "delete.php"

Full path: /home2/santhos2/public_html/bharath-coe.firstmatrix.in.net/api/courses/delete.php
File size: 1.95 KiB (1995 bytes)
MIME-type: text/x-php
Charset: utf-8

Download   Open   Back

<?php
require_once '../../config/config.php';
header('Content-Type: application/json');

try {
    // Accept JSON or form-encoded payloads
    $rawInput = file_get_contents('php://input');
    $input = json_decode($rawInput, true);
    $id = 0;
    if (is_array($input) && isset($input['id'])) { $id = (int)$input['id']; }
    elseif (isset($_POST['id'])) { $id = (int)$_POST['id']; }

    if ($id <= 0) {
        echo json_encode(["status"=>"error","message"=>"Invalid ID."]); exit;
    }

    // Pre-check dependent records for clearer UX
    // 1) Students referencing this course
    try {
        $cnt = $pdo->prepare('SELECT COUNT(*) FROM students WHERE course_id = ?');
        $cnt->execute([$id]);
        $studentDeps = (int)$cnt->fetchColumn();
        if ($studentDeps > 0) {
            http_response_code(409);
            echo json_encode(["status"=>"error","message"=>"Cannot delete this course because ".$studentDeps." student(s) are linked to it. Reassign or remove those students first, or deactivate the course."]); 
            exit;
        }
    } catch (Throwable $e) { /* ignore pre-check failure */ }

    // Attempt deletion, catch FK errors
    try {
        $stmt = $pdo->prepare("DELETE FROM courses WHERE course_id=?");
        $stmt->execute([$id]);
    } catch (PDOException $e) {
        $info = $e->errorInfo ?? null; // [sqlstate, driver_code, message]
        if (is_array($info) && isset($info[1]) && (int)$info[1] === 1451) {
            http_response_code(409);
            echo json_encode(["status"=>"error","message"=>"Cannot delete this course because it is referenced by related records. Remove or reassign dependent data first."]); 
            exit;
        }
        throw $e;
    }

    echo json_encode(["status"=>"success","message"=>"Course deleted successfully."]);    
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(["status"=>"error","message"=>"Request failed. Please try again."]); // keep API JSON clean
}
?>

PHP File Manager