How do I INSERT and DELETE linked MySQL tables using mysqli and PHP?

Viewed 44

I have three tables: all_students, all_parents, and students_parents (this is the link table).

I insert entries like this:

$sql = "INSERT INTO all_students (name, email) VALUES (?,?);";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $name, $email);
$stmt->execute();
if (mysqli_connect_errno()) { 
    $conn->close(); 
    echo "Error: ". mysqli_connect_error();
    exit;
}
$last_student_id = $conn->insert_id;

// get the parents $name and $email from POST data...
$sql = "INSERT INTO all_parents (name, email) VALUES (?,?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $name, $email);
$stmt->execute();
if (mysqli_connect_errno()){ 
    $conn->close(); 
    echo "Error: ". mysqli_connect_error(); 
    exit; 
}
$last_parent_id = $conn->insert_id;

// insert both parentid and studentid into students_parents table
$sql = "INSERT INTO students_parents (student, parent) VALUES (?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $last_student_id, $last_parent_id);
$stmt->execute();
// close, etc..

Is there a way to automatically delete the parent and student ID entries from students_parents table in the FUTURE if, let's say, I want to delete a student from the all_students. Or do I have to SELECT from the table again and find the id then delete?

Also, is there a better way to do this, or is my method now acceptable?

P/S I know that some students don't have parents, but for simplicity sake, I just put "parent" as the table name. It could be a guardian and not really the parent.

0 Answers
Related