在modelSlikeVrijednost
中,我引用了model
- s主键。 ModelSlikeVrijednost
可以包含大量图片(取决于用户)。我需要根据modelID
删除文件夹。
路径示例:/home/mainSite/public_html/site/img/1/1/
。
是否可以这样做?
代码:
if ($stmt = $mysqli->prepare("SELECT modelID FROM model WHERE proizvodacID='$id'")) {
$stmt->execute();
$stmt->bind_result($modelID);
while ($stmt->fetch()) {
$path="/home/mainSite/public_html/site/img/".$id."/".$modelID."/";
if ($stmt1 = $mysqli->prepare("SELECT modelSlikeVrijednost FROM modelSlike WHERE modelID='$modelID'")) {
$stmt1->execute();
$stmt1->bind_result($slike);
while ($stmt1->fetch()) {
if(is_null($slike)){
rmdir($path);
}
else{
$slikePath="/home/mainSite/public_html/site/".$slike;
if($slikePath!=$path){
unlink($slikePath);
}
rmdir($path);
}
}
$stmt1->close();
}
else {
printf("Prepared Statement Error: %s\n", $mysqli->error);
}
}
$stmt->close();
}
我收到错误:Prepared Statement Error: Commands out of sync; you can't run this command now Prepared Statement Error: Commands out of sync; you can't run this command now
答案 0 :(得分:3)
不,你不能......你需要遍历所有结果,关闭光标或使用单独的连接。
然而,无论如何,你想要做的事情更好地通过加入完成...
SELECT ms.modelSlikeVrijednost, m.modelID FROM model m, modelSlike ms
WHERE ms.modelID= m.modelID
AND m.proizvodacID ='$id'
这将为您提供每行所需的所有信息。
但是你也错误地使用预准备语句。你不应该直接传递php变量,你应该将它们作为参数绑定到查询:
$sql = 'SELECT ms.modelSlikeVrijednost, m.modelID FROM model m, modelSlike ms'
.' WHERE ms.modelID= m.modelID'
.' AND m.proizvodacID = ?';
if($stmt = $mysqli->prepare($sql)) {
// bind the $id to the parameter as an integer
$stmt->bind_param('i', $id);
$stmt->execute();
// bind the fields of the result to the same variables you had before
$stmt->bind_result($slike, $modelID);
// less prone to error if we only type this manually once :-)
$basePath = "/home/mainSite/public_html/site";
while($stmt->fetch()) {
$path= $basePath . "/img/".$id."/".$modelID."/";
$slikePath = $basePath . "/" . $slike;
if(is_null($slike)){
rmdir($path);
} else {
if($slikePath!=$path) {
unlink($slikePath);
}
rmdir($path);
}
}
}
答案 1 :(得分:2)
不要使用裸mysqli API
给自己一个帮助班,比如safemysql
然后你的代码将是
$models = $db->getCol("SELECT modelID FROM model WHERE proizvodacID=?i",$id);
foreach($models as $modelID) {
$path = "/home/mainSite/public_html/site/img/$id/$modelID/";
$sql = "SELECT modelSlikeVrijednost FROM modelSlike WHERE modelID=?i";
$sarr = $db->getCol($sql, $modelID));
foreach($sarr as $silke) {
if(!$slike)) {
rmdir($path);
} else {
$slikePath="/home/mainSite/public_html/site/".$slike;
if($slikePath!=$path){
unlink($slikePath);
}
rmdir($path);
}
}
}
}
但是,是的,最好在一个查询中执行,比如prodigitalson说:
$sql = "SELECT ms.modelSlikeVrijednost, m.modelID FROM model m, modelSlike ms
WHERE ms.modelID= m.modelID AND m.proizvodacID=?i";
$sarr = $db->getCol($sql, $id);
foreach($sarr as $silke) {
if(!$slike)) {
rmdir($path);
} else {
$slikePath="/home/mainSite/public_html/site/".$slike;
if($slikePath!=$path){
unlink($slikePath);
}
rmdir($path);
}
}
}
主要思想是从查询中获取您的数据,然后使用它。