Search code examples
phpdelete-fileunlink

Tying in unlink() with sql delete


I have setup a simple while loop which returns all images in a table along with their respective title and description so that users can update the details accordingly for each image.

The images are returned with a checkbox which allows user to delete images as per php code

if($_POST['doDelete'] == 'Delete') {

if(!empty($_POST['u'])) {
    foreach ($_POST['u'] as $uid) {
        $id = filter($uid);
        mysql_query("delete from landscape where id='$id'");
    }
 }
 $ret = $_SERVER['PHP_SELF'] . '?'.$_POST['query_str'];;

 header("Location: $ret");
 exit();
}

How do I incorporate the unlink() function into the page so that the file is also removed from the server?


Solution

  • If the images are named in accordance with the ID:

    foreach ($_POST['u'] as $uid) {
        $id = filter($uid);
        mysql_query("delete from landscape where id='$id'");
        unlink( '/path/to/images/' . $id);
    }
    

    Be sure to properly escape $id before using it in your query or in the unlink statement.