Reputation: 139
I have a field in a sql database called time_stamp
that timestamps when the record was added to the database. I have another field called 'TTL', which will have either 1, 2, or 3 stored in it (each number within this field represents a day). Can I have a php script where the deletion of the record is determined by the 'TTL' field?
For instance a record is added at noon today, with a 'TTL' of 2, can I have a script that deletes that same record at noon two days from now?
What would be the best way to do this, and do I really need both fields to execute this?
Upvotes: 1
Views: 134
Reputation: 15399
Your best method for running this script is attaching it to cron
and having it run on a given interval.
Then, in order to program the record deletion, you'll need to run the following query:
DELETE FROM records WHERE UNIX_TIMESTAMP(time_stamp) + TTL * 86400 <= CURRENT_TIMESTAMP()
time_stamp
is your record creation value - let's say it's equal to 1000000. 86400 is the amount of seconds in a day. TTL
is the amount of days after time_stamp
that you want the file deleted. So if TTL
is 2 and 1000000 was the timestamp for July 10th, we are basically comparing:
1000000 + 86400 * 2 <= CURRENT_TIMESTAMP
Now, let's say that today is July 12th. This means it's 2 days (86400 * 2 seconds) after July 10th. Thus,
CURRENT_TIMESTAMP = July 10th timestamp + 2 days worth of seconds
= 1000000 + 86400 * 2
Which implies CURRENT_TIMESTAMP >= 1000000 + 86400 * 2
for all points in time during and after July 12th, thus deleting the record.
This will delete the records daily for you while your server is running. Enjoy and good luck!
Upvotes: 1