Hello,

I am writing a delete script to delete sql data of an uploaded picture:

studentmgt.php

if (!empty($_REQUEST['student_id']))
        {
        $student_id = $_REQUEST['student_id'];
        $result = mysql_query("DELETE FROM student WHERE student_id =".$student_id) or die(mysql_error());
        echo $result;
        $confirmation = !$result ? "Gagal menghapus data." : "Data telah terhapus."; 
        }

Just one problem, the actual picture file (student picture) still remains in the server. I have the file name stored in the sql data, but do not know how to delete the actual file.

Please help.

Thanks in advance.

Recommended Answers

All 5 Replies

Store the filename in a variable before running your delete query, then use unlink to delete it. It pains me to see you using mysql_* but I'll use it in this case to stay consistent with your code

if (!empty($_REQUEST['student_id'])) {
    $student_id = $_REQUEST['student_id'];

    // Query to get student picture filename
    $result = mysql_query("SELECT student_picture FROM student WHERE student_id =".$student_id) or die(mysql_error());
    $row = mysql_fetch_assoc($result);
    $pic_filename = $row['student_picture'];

    // Now let's delete the student from db
    $result = mysql_query("DELETE FROM student WHERE student_id =".$student_id) or die(mysql_error());

    // If data was successfully deleted, get rid of the picture too
    // I know you have a "confirmation" down below, but I just wanted to list this as an example:
    if($result) {
        unlink($pic_filename);
    }

    echo $result;
    $confirmation = !$result ? "Gagal menghapus data." : "Data telah terhapus."; 
}

Thanks. the link thing almost works. Except that I have this error message:

Warning: unlink(../upload/): Permission denied in C:\xampp\htdocs\squprime\administrator\student\profile.php on line 173

(I would like to erase this error message eventhough the picture is already deleted), like how?

student/profile.php

if($result){
                unlink('../upload/'.$pic_filename);
            }

Nevermind, I tried once again and no error message.

Thanks.

Wait! I keep seeing this warning appearing:

Warning: unlink(../upload/): Permission denied in C:\xampp\htdocs\squprime\administrator\teacher\profile.php on line 173

line 173:

if($result){
                unlink('../upload/'.$pic_filename);
           }

Why is it?

Check your "upload" directory permissions bud. Since you're deleting a file in that directory, you need write access, not just read access. chmod() should be 0777.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.