1

我想根据图像的文件名从数据库中删除一行。假设我在下面有 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 表中删除该行行包含与图像表中的 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_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();  
4

1 回答 1

1

您可以使用JOIN查询在单个查询中从多个表中删除。我认为这种陈述对你有用:

$sql = "
DELETE img, img_q
FROM Image AS img
LEFT JOIN Image_Question AS img_q
    ON img_q.ImageId = img.ImageId
WHERE img.ImageFile = ?";
于 2012-09-21T00:56:14.857 回答