Jeno Jeno - 3 months ago 16
PHP Question

Delete more than one file using unlink

Hi i got this simple delete script but i can only get it too delete 1 file in the folder, and i tried some diffrent stuff trying to loop the unlink but it wont work anyone knows how it is done?

$id = $_GET['id'];
$sql_get = "SELECT shop.id, shop.overskrift, shop.pris, shop.text, shop_pictures.ShopPictures_id, shop_pictures.shop_pictures_file
FROM shop INNER JOIN shop_pictures
ON shop.id = shop_pictures.fk_shop_pictures_shop_id WHERE Id=$id";
$result_get = mysqli_query($connection, $sql_get);
$row = mysqli_fetch_all($result_get);

$sql = "DELETE FROM shop WHERE Id=$id";
$result = mysqli_query($connection, $sql);

$sql = "DELETE FROM shop_pictures WHERE fk_shop_pictures_shop_id=$id";
if(!empty($row)) {
foreach($row as $data) {
unlink('../../img/shop_pictures/'.$data['shop_pictures_file']);
}


}
$result = mysqli_query($connection, $sql);

//header('Location: ../members.php');exit;

Answer

Your code is incredibly susceptible to SQL Injection so you may want to address that. However, you need to loop through your results.

$row = mysqli_fetch_array($result_get); only fetches one result, make sure you use something like this instead:

$row = mysqli_fetch_all($result_get, MYSQLI_ASSOC);

if(!empty($row) {
    foreach($row as $data) {
        unlink('../../img/shop_pictures/'.$data['shop_pictures_file']);
    }
}

Alternatively you could do something like this:

while ($row = mysql_fetch_array($result_get)) {
    unlink('../../img/shop_pictures/'.$row['shop_pictures_file']);
}

That should point you in the right direction.