我看到我的問題可能已經有了答案,並且「在mysql中,刪除級聯不工作」似乎更類似.....但我什麼都看不到建議在那個職位上爲我工作。mysql PDO ON DELETE CASCADE - 不工作
問題是,當我刪除一個配方時,我希望它的附件也被刪除(一步一步,此刻我只是試圖從mysql表中刪除它,而不是從它所在的文件夾存儲)。
我在這裏發佈一個類似的問題,但關於如何創建MySQL觸發器,我設置了外鍵和刪除級聯,所以我雖然,當一個配方得到刪除,附件以及,但它絕對沒有發生對附件....我做錯了什麼?
下一頁到每個配方我有一個按鈕來刪除它:
echo '<a class="toLink" href="delete_recipe.php?id=' . $recipe['id'] . '" title="delete recipe" onclick="return confirm(\'Are you sure you want to delete this recipe?\');">Delete recipe</a>';
在delete_recipe.php:
<?php require 'includes/functions.php';
$recipeId = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);
if(delete_recipe($recipeId) == true) {
header('Location: index.php');
exit;
} else {
$error_message = "Could not delete recipe";
}
在functions.php中:
function delete_recipe($recipe_id = ':recipe_id') {
include 'db_connection.php';
try {
$sql = "DELETE FROM recipes ";
$sql .= "WHERE id =:recipe_id ";
$sql .= "LIMIT 1";
$results = $conn->prepare($sql);
$results->bindParam(':recipe_id', $recipe_id, PDO::PARAM_INT);
if($results->execute()) {
echo '1 row has been removed';
}
$conn = null;
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage() . '<br />';
return false;
}
return true;
}
我想我已設置外鍵和「級聯刪除」正確.....如果我這樣做:
顯示創建表的食譜:
| recipes | CREATE TABLE `recipes` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`attachment_id` int(11) NOT NULL,
`chef_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `fk_recipes_attachments1_idx` (`attachment_id`),
KEY `fk_recipes_chefs1_idx` (`chef_id`),
CONSTRAINT `fk_recipes_attachments1` FOREIGN KEY (`attachment_id`) REFERENCES `attachments` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_recipes_chefs1` FOREIGN KEY (`chef_id`) REFERENCES `chefs` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 |
顯示創建表的附件:
| attachments | CREATE TABLE `attachments` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`attachment_path` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 |
任何想法,爲什麼它不會刪除屬於我刪除配方中的附件表中的附件?
謝謝
[「FOREIGN KEY子句在*子表*中指定」](http://dev.mysql.com/doc/refman/5.7/en/create-table-foreign-keys.html) –
I也會猜測MySQL的錯誤日誌會對此產生阻礙,並給你一個打擊一些光的呃... – junkfoodjunkie
馬特吉布森,你能澄清我嗎?所以,在食譜中,我有一個attachment_id,屬於附件表中的主鍵,所以我應該把這個id作爲外鍵放在附件表上?!!?!!! –