Hi Stackoverflow users,
I have a problem with deleting data in two tables with their foreign keys.
Intro: I created a blogging website hosted locally with xampp and written in PHP and MySQL. Basically I have the functionality of it done, but that's not why I'm here. I have a problem with deleting data from two tables at once.
Scenario:
The structure of part of my database is shown in the picture below
Let's say a user created a post for his website, the post is stored in table blog_entries, username is referenced from user_table and a unique entry_id is generated for that post.
I created a separate table for storing comments added to a particular post called entry_comments. With entry comments, i also reference username from user_table so that people can tell who made the comment and referenced entry_id from blog_entries for that post.
The problem is when the user goes to their profile in order to delete a post, I want the database to delete all the comments associated with that post before deleting the post itself.
My Code
I achieved this by deleting the comments for a post first before deleting the post itself, but I want to know if there is a way to delete data from both tables by using a single query as shown below.
$entry_id = mysqli_real_escape_string($DBConn, $_GET['entry_id']);
$query1 = "DELETE FROM $entry_comments WHERE entry_id='$entry_id'";
$result1 = mysqli_query($DBConn, $query1);
if(!$result1){
//display error message if query failed
}
else{
$_GLOBAL['message'] = "Comments with id $entry_id has been deleted!!!";
}
$query2 = "DELETE FROM $blog_entries WHERE entry_id='$entry_id'";
$result = mysqli_query($DBConn, $query2);
if(!$result){
//display error message if query failed
}
else{ $_GLOBAL['message'] .= "Entry with id $entry_id has been deleted!!!";
include 'profile.php'; //redirect
}
So i tried shortening the query to use a Join query in order to delete data from two rows with this query but it didn't work.
DELETE FROM $blog_entries, $entry_comments
WHERE $blog_entries.username = $entry_comments.username
AND entry_id='$entry_id'
or I used
DELETE be, ec
FROM $blog_entries be
JOIN $entry_comments ec ON be.username = ec.username
WHERE be.entry_id = '$entry_id'
I researched the problem and the closest answer I found to my problem was this: How to delete from multiple tables in MySQL? and I tried to rewrite my sql code to match it but would still get an error saying it has problems deleting due to foreign keys, and I can't figure out what I'm doing wrong.
451 - Cannot delete or update a parent row: a foreign key constraint fails (`thenefariousblog`.`entry_comments`, CONSTRAINT `entry_comments_ibfk_2` FOREIGN KEY (`entry_id`) REFERENCES `blog_entries` (`entry_id`))
Sorry if this post feels a little bit long-winded, but i'm trying to explain the problem I have as much as possible in order to get the best feedback