Delete expired entries in MYSQL

For those who want to delete items in a MySQL database based on a date field  the process is very easy.

First of all you need a DATE field, for example a coupon expiration date. the data is saved in the following format: YYYY-MM-DD

Then all you need to delete older items is this:

DELETE FROM coupons WHERE expiration < '2010-12-03'

make sure that your date is set between single quotes ( ‘ ) if you don’t then MySql will treat this as an arithmetic operation 2010 – 12 – 03 =  1995

you can use the php function date to generate a time stamp for today

$today = date(“Y-m-d”); // will output something like 2010-12-03

or for yesterday you could use something like

$yestday = date(“Y”).’-‘.date(“m”).’-‘. date(“d”)-1;

you can subtract an integer to either thedate(“Y”) or date(“m”) to go back on years or months

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.