简体   繁体   中英

How can i delete data from database with foreign key constraint in mysql using php pdo

I have three Tables in database.

table 1

projects

PK ProjectID

table 2

students

PK RegNo
FK ProjectID

table 3

progress

FK RegNo

Now the thing I want to perform a delete operation when I delete the record from a project it should be deleted from students, as students primary key is also present as foreign key progress table, so it should also delete RegNo from progress table. How I can achieve this as the best possible way. Thanks in advance.

$query = "DELETE students, progress from students inner join progress on progress.RegNo=students.RegNo where students.ProjectID='$id';DELETE FROM projects where projects.ProjectID='$id'";

//$conn->exec($query);
$stmt = $conn->prepare($query);
$stmt->execute();

it gives foreign key constraint violation

It could be easier to split deletes into separate queries.

 DELETE FROM `progress` 
        WHERE `RegNo` IN(
          SELECT `RegNo` FROM `students` WHERE ProjectID = '$id'
        ); 

 DELETE FROM `student` WHERE `ProjectID` = '$id';
 DELETE FROM `projects` WHERE `ProjectID` = '$id';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM