I have literally tried everything i've found on the internet about deleting from multiple tables in same query, but it just ends up deleting from the first table(Posts)..
So how does one do this the correct way with php and pdo?
examples of what i've tried=
$dsn = "DELETE FROM Posts, Comments USING Posts, Comments WHERE Posts.ID = Comments.PostID AND Comments.PostID=:my var";
$dsn = "DELETE FROM Posts LEFT JOIN Comments ON `Comments.PostID` = `Posts.ID` WHERE `Posts.ID`=:tit";
$dsn = "DELETE Posts , Comments FROM Posts INNER JOIN Comments WHERE Posts.ID = Comments.PostID and Posts.ID =:myvar";
The tables looks as following:
TABLE: Posts
ID(PK AI)
Title(VARCHAR)
Post(VARCHAR)
Author(VARCHAR)
Date(DATETIME)
TABLE: Comments
ID(PK AI so all comments get unique id's)
Name(VARCHAR)
Comment(VARCHAR)
Date(DATETIME
PostID(INT)
You have different ways to solve this:
1- delete with inner join
$dsn = "DELETE Posts.*, Comments.* FROM Posts INNER JOIN Comments WHERE Posts.ID = Comments.PostID and Posts.ID =:myvar";
2- delete cascade, drop if exist foreing key and execute this:
ALTER TABLE Comments
ADD CONSTRAINT fk_postid
FOREIGN KEY (PostID)
REFERENCES Posts(ID)
ON DELETE CASCADE;
3- using trigger after delete in the table Posts
delimiter $$
CREATE TRIGGER `after_delete_Posts`
AFTER DELETE ON `Posts`
FOR EACH ROW
BEGIN
DELETE FROM Comments where PostID = OLD.id;
END
$$
delimiter ;