gpt4 book ai didi

php - 多个准备语句的优雅解决方案

转载 作者:行者123 更新时间:2023-11-29 20:24:59 24 4
gpt4 key购买 nike

我试图以更好的方式解决的问题是删除带有标签的图像的文件夹。因此,对于每个图像,我需要删除

-图像本身

-来自三个数据库(img_offer、img_member、img_horses)的该图像的标签

目前,我获取要删除的文件夹的所有图像 ID,然后使用四个不同的查询迭代这四次,这似乎效率很低。

主要问题是,据我所知,您不能同时打开多个准备语句,并且在每次迭代中创建新的语句似乎也是违反直觉的。

我认为最好的方法是像多个查询准备语句一样,但我找不到类似的东西,所以也许这里有人知道如何以更干净的方式解决这个问题

我的想法是这样的

$multiplePreparedStatement= "DELETE this FROM that WHERE id=?;
DELETE this2 FROM that2 WHERE id2=?;
DELETE this3 FROM that3 WHERE id3=?;";
$preparedStmt = $conn->prepare($multiplePreparedStatement);
foreach($imgArray as $imgId){
$preparedStmt->bind_param("iii", $imgId, $imgId, $imgId);
$preparedStmt->execute();
}
$preparedStmt->close();

但我认为这行不通,因为准备好的语句不支持多个 SQL 查询,是吗?

这是我当前的代码:

       $id=$_GET['deleteAlbum'];
$getImages = "SELECT image_id AS id
FROM Images
WHERE folder_id = ?";
$deleteImage="DELETE FROM Images
WHERE image_id=?";
$deleteOffer = "DELETE FROM Images_Offers
WHERE image_id=?";
$deleteHorse = "DELETE FROM Images_Horses
WHERE image_id=?";
$deleteTeam = "DELETE FROM Images_Team
WHERE image_id=?";

//get all image ids
$ImgStmt=$conn->prepare($getImages);
$ImgStmt->bind_param("i", $id);
$ImgStmt->execute();
$ImgStmt->bind_result($id);
$imgToDelete = array();
while($ImgStmt->fetch()){
array_push($imgToDelete, $id);
}
$ImgStmt->close();

$stmt=$conn->prepare($deleteOffer);
foreach ($imgToDelete as $imgId){
$stmt->bind_param("i",$imgId);
$stmt->execute();
}
$stmt->close();

$stmt=$conn->prepare($deleteHorse);
foreach ($imgToDelete as $imgId){
$stmt->bind_param("i",$imgId);
$stmt->execute();
}
$stmt->close();

$stmt=$conn->prepare($deleteTeam);
foreach ($imgToDelete as $imgId){
$stmt->bind_param("i",$imgId);
$stmt->execute();
}
$stmt->close();

$stmt=$conn->prepare($deleteImage);
foreach($imgToDelete as $imgId){
unlink("../assets/img/images/img".$imgId.".jpg");
$stmt->bind_param("i",$imgId);
$stmt->execute();
}
$stmt->close();

我也有创建多个连接的想法,但我认为如果例如当我仍然有一个迭代图像的查询时删除图像。

最佳答案

您根本不必迭代image_id(至少对于 SQL 数据来说不需要)。您可以一次性从数据库中删除与特定 folder_id 关联的所有内容:

DELETE Images, Images_Offers, Images_Horses, Images_Team
FROM Images
LEFT JOIN Images_Offers ON Images_Offers.image_id = Images.image_id
LEFT JOIN Images_Horses ON Images_Horses.image_id = Images.image_id
LEFT JOIN Images_Team ON Images_Team.image_id = Images.image_id
WHERE folder_id = ?;

当然,在此之前您应该取消链接实际文件。

关于php - 多个准备语句的优雅解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39344693/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com