【发布时间】:2012-09-20 23:31:09
【问题描述】:
我想根据图像的文件名从数据库中删除一行。假设我在下面有 2 个表:
Image Table:
ImageId ImageFile
01 cat.png
02 dog.png
03 dog_2.png
Image_Question Table:
ImageId SessionId QuestionId
01 AAA 4
02 ABD 1
03 RTD 11
假设在我的应用程序中我删除了文件图像 dog_2.png,然后我希望它删除图像表中声明 dog_2.png 的行(这工作正常)并能够从 Image_Question 中删除该行该行包含与 Image Table 中的 ImageId 和 ImageFile 名称关联的相同 ImageId 的表(这不起作用)。
因此,对于上面的示例,删除后 2 个表现在应该如下所示:
Image Table:
ImageId ImageFile
01 cat.png
02 dog.png
Image_Question Table:
ImageId SessionId QuestionId
01 AAA 4
02 ABD 1
但它不会从 Image_Question 表中删除该行,我怎样才能删除该行?
以下是从图像表中删除行的完整代码,其中包含大部分已设置但在从图像问题表中删除行时尚未完全完成的代码:
$image_file_name = $_GET["imagefilename"];
$img = "ImageFiles/$image_file_name";
echo "$image_file_name was Deleted";
unlink("ImageFiles/$image_file_name");
$imagedeletesql = "DELETE FROM Image WHERE ImageFile = ?";
if (!$delete = $mysqli->prepare($imagedeletesql)) {
// Handle errors with prepare operation here
}
//Don't pass data directly to bind_param; store it in a variable
$delete->bind_param("s",$img);
$delete->execute();
if ($delete->errno) {
// Handle query error here
}
$delete->close();
$imagequestiondeletesql = "DELETE FROM Image_Question WHERE ImageId = ?";
if (!$deleteimagequestion = $mysqli->prepare($imagequestiondeletesql)) {
// Handle errors with prepare operation here
}
// Don't pass data directly to bind_param; store it in a variable
$deleteimagequestion->bind_param("s",....);
$deleteimagequestion->execute();
if ($deleteimagequestion->errno) {
// Handle query error here
}
$deleteimagequestion->close();
【问题讨论】:
-
您使用的是哪个存储引擎?如果您使用
InnoDB,则可以使用ON DELETE CASCADE添加外键(请参阅dev.mysql.com/doc/refman/5.1/en/…),这样您就无需在应用程序代码中处理此问题。 -
我不知道它是哪个存储引擎,但如果我需要使用 DELETE CASCADE,您能否在答案中告诉我代码应该是什么样的?
-
如果你有 InnoDB,并使用
ON DELETE CONSTRAINT添加一个外键,那么你可以删除所有从Image_Question删除记录的 PHP 代码,因为一旦你从Image,它的所有子记录也会立即被删除。 -
那么 SQL (phpmyadmin) 中的代码应该是:
ALTER TABLE Image_Question ADD FOREIGN KEY('ImageId') REFERENCES Image('ImageId') ON DELETE CASCADE吗? -
是的,没错,只是我不确定
ImageId周围的单引号。反引号会更好,恕我直言。