我看到我的问题可能已经有了答案,并且“在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作为外键放在附件表上?!!?!!! –