Jump to content

How to delete MySQL records after a certain time?


Vince889

Recommended Posts

How do you delete MySQL records after a designated time? Does it require a cron-job?

 

Allow me to explain the situation:

I am submitting a record to the database, included with a mysql timestamp and the number of hours that the the records should be kept.

So an example record is: "UserA |  2009-12-08 12:30:52 | 1"

Meaning, I want PHP to delete 'UserA' in one hour. Now mind you, there will be a lot of different records in my database with different deletion times.

 

I was assuming that I would have to do something extremely verbose and annoying like looping through each record, checking the timestamps and converting the 'hours' into timestamps somehow, then checking if the record is due to be deleted... Sounds really complicated! Is there another way to do it?

 

out of everything in php, i find date/time calculation to be the hardest

Link to comment
Share on other sites

First off, make it easy on yourself. Instead of storing the hours before deletion, store the timestamp of deletion (if you absolutely need the time to deletion, then store that too). Then, you do not need to do any calculations when it comes time to delete, simply run a simple query such as:

 

DELETE FROM table
WHERE deleteTime < NOW()

 

As ym_chaitu stated above you could do this through a CRON job (google for more info). However, do you really need to delete the records? You could make the delete time an expire time. Then just use the expire time to exclude any expired records when doing the normal queries.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.