简体   繁体   中英

Deleting records from SQL table when date is exceeded

I'm currently developing a system to manage students that are on a report in school but I've fallen across a stumbling block. In my SQL table ('onreport')there is a field called 'duration' I want any records where the date stored stored in this row is passed to be deleted, Ie the report has expired.

    <?php
    include('connect.php'); //connect to the database
    $today = new DateTime("now");
    $f_today=$today->format('Y-m-d');
    mysql_query('DELETE FROM onreport WHERE duration ==$f_today');
    //print('$f_today')
    ?>

I realise that this may not be the most efficient method even if it did work but I was getting desperate! I know that the code is running because including the commented out print statement prints today's correct date in the same format as the format in the table. The duration column is type 'date' and in the table it is displayed as yyyy-mm-dd

It seems that instead of comparing dates, you are comparing string, which is generally considered a bad practice. But since you didn't post your DB schema it is hard to tell.

However if you to want to remove every report posted before today, you can use pure SQL query assuming that the field duration is of DATE type:

DELETE FROM onreport WHERE TIMESTAMPDIFF(DAY,CURDATE(),duration)>0

This queries compare two dates : CURDATE() which is the current server time with the value of duration and return a result in number of days. If this value is greater than zero, the row is removed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM