php - 不删除第二个表中的行

标签 php mysql mysqli

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

最佳答案

您可以使用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 = ?";

关于php - 不删除第二个表中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12522402/

相关文章:

php - 在 PHP 中向正则表达式添加注释的正确方法

php - Symfony2 : How to go back to a page where the request of a form was send from

通过 Connector/NET 使用 MySQL 的 C#

php - 在 mysqli_fetch_array 中添加依赖于 php IF 语句的 CSS 样式

php - 如何使用 mysqli_fetch_array() 两次?

php - 嵌套多级类别的更动态的方式

php - 按年份和月份获取我的博客新闻,显示标题和创作数据

mysql 我可以按两个日期中最早的日期排序吗?

mysql - 如何在 Laravel 中获取相似的产品标签?

php - 给出警告 : mysqli_error() expects exactly 1 parameter, 0