【问题标题】:Not deleting row in second table不删除第二个表中的行
【发布时间】: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 周围的单引号。反引号会更好,恕我直言。

标签: php mysql mysqli


【解决方案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 = ?";

【讨论】:

  • 我想在mysqli中使用bind_params,因为它更安全,是不是意味着代码是这样的:DELETE Image, Image_Question FROM Image INNER JOIN Image_Question WHERE Image.ImageId= ? AND Image.ImageFile = ?; ... $delete->bind_param("ss",Image_Question.ImageId ,$img);
猜你喜欢
  • 1970-01-01
  • 2014-01-30
  • 2013-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-17
  • 1970-01-01
  • 2017-02-15
相关资源
最近更新 更多