Search code examples
phpcheckboxbackground-imageunlink

Using checkboxes to delete multiple images from db successfully but doesn't unlink files from folder


I have a problem with the unlink() function in PHP. I have used a checkbox for deleting images or uploded video files.

Multiple images or videos are deleted sucessfully from the database but not from the local folder using unlink().

There are no errors but when I select all checkboxes and press delete then all files from the database are deleted but only the first file is unlinked.

this is my code:

<?php // for delete checked video php script

include('config.php');

if(isset($_POST['delete'])) {
    $checkedCandidates = 0;
    $id = implode(",", $_POST['deletecb']);

    $checkedCandidates = count($id);

    if ($checkedCandidates < 1) {
        echo "<div id=\"errormsg\"> You need to check at least one video for delete. </div>";
        echo "<script>setTimeout(\"location.href = 'video_upload.php';\",3000);</script>";
    } else {
        $result=mysqli_query($connection,"SELECT * FROM video_gallery where id_vid IN($id) and users_name='$login_session'");

        while ($row=mysqli_fetch_assoc($result)) {
            $fname=$row[FILE_NAME];

            $Path="data/58f60f2e09f07_jay/videos/$fname";
            if (file_exists($Path)){
                if (unlink($Path)) {
                    echo "success";
                } else {
                    echo "fail";
                }
            } else {
                echo "file does not exist";
            }
        }
        $query1=mysqli_query($connection,"delete from video_gallery where id_vid IN($id) and users_name='$login_session'");
        if($query1) {
            echo "<div id=\"successmsg\"> delete successfully </div>";
        } else {
            echo "<div id=\"errormsg\"> failed operation!!</div>";
        }
    }
}
?>

Solution

  • try print_r($row); and check the key name of the file name change this line as you are accessing an array item

    $fname=$row[FILE_NAME]; 
    

    to

    $fname=$row['the actual name of the field'];