I've got a problem with deleting the uploaded images.
It inserts in the database and uploads just fine but it won't delete.
Example: I have two tables, modelImages and Model. In Model I save the path of one main image, but in modelImage there can be a lot of them. The tables are linked via modelID.
This is an example how the path looks like:img/1/1/someImageName.png.
(first 1 - makerID, second 1 - modelID).
include('connect.php'); //connect to database
$modelID=$_GET['modelID'];
$makerID=$_GET['makerID'];
$path="img/".$makerID."/".$modelID."/";
if ($stmt = $mysqli->prepare("SELECT images FROM modelImages WHERE modelID='$modelID'")) {
$stmt->execute();
$stmt->bind_result($images);
while ($stmt->fetch()) {
if($images!=$path){
unlink($images);
}
}
$stmt->close();
}
else {
printf("Prepared Statement Error: %s\n", $mysqli->error);
}
if ($stmt = $mysqli->prepare("SELECT mainImage FROM model WHERE makerID='$makerID' AND modelID='$modelID'")) {
$stmt->execute();
$stmt->bind_result($mainImage);
while ($stmt->fetch()) {
if($mainImage!=$path){
unlink($mainImage);
}
}
$stmt->close();
}
else {
printf("Prepared Statement Error: %s\n", $mysqli->error);
}
When I just use the first code , it deletes all the images from the modelImages table and if I just use the second code, it deletes the one image from the model table.
But if I use them together I get the unlink()
error:
Warning: unlink(img/1/1/image1.png) [function.unlink]: No such file or directory in /home/...
Warning: unlink(img/1/1/image2.png) [function.unlink]: No such file or directory in /home/...
Warning: unlink(img/1/1/image3.png) [function.unlink]: No such file or directory in /home/...
Warning: unlink(img/1/1/image4.png) [function.unlink]: No such file or directory in /home/...
Conclusion: The unlink won't work if I use both of the querys together.
Don't use relative paths unless a) you are absolutely sure, what the current work directory is (see getcwd()
), or b) it is intended, that the path is located relative to difference work directories (like in workdirectory-aware CLI-tools). Always use, or create absolute paths
"/path/to/img/".$makerID."/".$modelID."/";
__DIR__ . "/../path/to/img/".$makerID."/".$modelID."/";
I would prefer the second one, because it is more portable.