我正在尝试从不在表格中的文件夹中删除图像 我离解决方案只有一条线 我不知道如何将故事查询结果与图像文件夹内容进行比较 这就是我所拥有的
$link = mysqli_connect($dbhost, $dbuser, $dbpass) or die("Unable to Connect to '$dbhost'");
$like = scandir('users/russromei');
foreach ($like as $thisFile) {
$rs = mysqli_query($link,"SELECT value FROM ppbv79_listings_media WHERE value like %$thisFile%");
if($thisFile != "." and $thisFile != ".."){
echo $thisFile."<br>";
**** NEED TO COMPARE $thisfile with $rs???
/* if($thisFile != "." and $thisFile != ".."){
unlink ('sfbuyer/' . $thisFile);
} */
}
}
答案 0 :(得分:2)
使用预准备语句,因为@Martin表示您的代码可能容易受到SQL注入攻击。除此之外,这里有一个快速示例,说明如何删除该数据库中不存在的文件。
假设您有下表
------------------------
| ID | file |
------------------------
| 0 | img1.png |
| 1 | img2.png |
| 3 | someimage.png |
------------------------
你有一个包含这些图片的文件夹(img
):
img1.png, img2.png, someimage.png, random.png
在这里,你有两个选择;一种是获取文件中的每个图像并检查它是否存在于数据库中,如果不存在则删除它。
或你可以从数据库中选择所有图像并删除不存在的图像(这就是我将要做的)。
<?php
// first put all files into an array
$images = scandir('img');
// create a new empty array that going to hold all files from database
$files = [];
// new we select all files from database
// first make your query
$query = 'SELECT `file` FROM `myTable`';
// create mysqli object
$mysqli = new Mysqli('localhost','user','password','database');
// even though this query is not vulnerable to SQL injections
// I'm going to use a prepared statement
$stmt = $mysqli->prepare($query);
$stmt->execute();
$stmt->bind_result($file);
while($stmt->fetch()){ // insert all files into the array we created earlier
$files[] = $file;
}
$stmt->close();
$mysqli->close();
// now you have an array of all files from database and images in folder
// we are going to go through each image to check if it exist in the database
foreach($images as $img)
{
if(!in_array($img,$files)) {
// delete file
unlink('img/'.$img);
print("Deleted file [". $img ."]\n");
}
}
unset($img);
那就应该做到。