Search code examples
phpmysqlinner-join

Delete file from folder and mysql joined table


I have a file upload system where I can delete from MySQL DB and from the folder. The only problem is that all the files in the folder are deleted instead of just the single one. Each folder is a custom folder with a person's name.

I have a joined table where the id's of two tables are equal. I need the joined tabled to receive the name of the person to know the file location.

This is my working code so far where multiple files are deleted instead of the one I selected:

$analyse = mysqli_query($conn, "SELECT *
                                FROM analyse
                                INNER JOIN persons ON 
                                analyse.id_person = persons.id");

while ($row = mysqli_fetch_array($analyse)) {
    $img = $row['img_name'];
    $name= $row['name'];
    $frontname= $row['frontname'];
    $image_url = "../persons/{$name} {$frontname}/analyse/{$img}";
    $result = mysqli_query($conn, "DELETE FROM analyse WHERE id=$id");
    unlink($image_url);
    if($result){
        header('Location: ' . $_SERVER['HTTP_REFERER']);
    } else {
        echo "Failed to delete";
    }
}

For example: Person X with id 15 has three images with different ids but each time with the ID(15) of the person. I want to be able to delete the single selected file instead of all the files with id 15.

UPDATE I found the solution, the ID that came through for deleting was always the first in my DB row. The fetching of my array was wrong and my ID consequently too. Thanks for the answers.


Solution

  • Try using Limit 1 with your delete Query.

    $analyse = mysqli_query($conn, "SELECT *
                                    FROM analyse
                                    INNER JOIN persons ON analyse.id_person = persons.id");
    
    while ($row = mysqli_fetch_array($analyse)) {
        $img = $row['img_name'];
        $name= $row['name'];
        $frontname= $row['frontname'];
        $image_url = "../persons/{$name} {$frontname}/analyse/{$img}";
        $result = mysqli_query($conn, "DELETE FROM analyse WHERE id=$id LIMIT 1");
        unlink($image_url);
        if($result){
            header('Location: ' . $_SERVER['HTTP_REFERER']);
        } else {
            echo "Failed to delete";
        }
    }