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?
Your best method for running this script is attaching it to
cronand 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_stampis your record creation value – let’s say it’s equal to 1000000. 86400 is the amount of seconds in a day.TTLis the amount of days aftertime_stampthat you want the file deleted. So ifTTLis 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,
Which implies
CURRENT_TIMESTAMP >= 1000000 + 86400 * 2for 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!