• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 248
  • Last Modified:

proper use of unlink() for deleting record and image

hi...is there anyone who can show me the proper code for using unlink() ?  I have a table in the database with image path on it.

so it looks like this

listingID  | listingTitle | desc                        | image                  | date
1            |cheap psx  | good and cheap psx  | c:/images/psx.jpg | 8/5/2005

I wanted to delete this listing  once it get past its expiry date(30 days from the listing) The problem is the image would still be in the database...I have read a thing or two about unlink...but i'm not sure of its proper usage.

I am using php, mysql, apache and windows 2000. Thank you.

  • 2
  • 2
1 Solution
Hi spradjinata,

You have a full path in your database. That's kinda good. Not portable, but good for your case.
First, you get all of your "expired" images list.
$sql = 'SELECT * FROM table WHERE NOW() > DATE_ADD(`date`, INTERVAL 30 DAY)';
// assuming your `date` column is of DATETIME type
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
   $deleteSuccessful = @unlink($row['image']); // delete an image
   if ($deleteSuccessful) { // if delete successfull
        $sql = 'DELETE FROM table WHERE image = "'.$row['image'].'" AND listingID = "'.$row['listingID'].'"';
        mysql_query($sql); // delete record from database

German Rumm.
Do you want to delete the record or just the file ?

// DB settings
$result = mysql_query("SELECT * FROM table_name WHERE CURDATE() > DATE_ADD(date, INTERVAL 30 DAY)") or die("SQl error: " . mysql_error());
while($row = mysql_fetch_array($result)) {
  $filename = $row["image"];
  // Delete the file.
  if(file_exists($filename)) {
  $records[] = $row['listingID'];
// Delete the records in single query
if(isset($records) && !empty($records)) {
 $records_to_del = implode(',', $records);
 mysql_query("DELETE FROM table_name WHERE listingID IN ( $records_to_del )") or die("Delete query error: " . mysql_error());
 echo mysql_affected_rows() . ' records deleted.';
spradjinataAuthor Commented:
I want to delete both the record and the image. both solution looks great. I will award the points after I tried it. Thanks very much.
spradjinataAuthor Commented:
thank you ldbkutty....your answer is perfect...thanks.....sorry german rumm...your answer doesn't work...i wanted to give you points but i can't split it....(the split point is missing)......thanks though.
>> thank you ldbkutty....your answer is perfect...thanks.....

>> (the split point is missing)

If you wish, I can reopen the question or split the points.

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now