0

I have activity logs stored in my mysql database, each with a registered datetime. I am trying to write a short php script to delete all logs that are older than 60 days. I am having trouble trying to compare the times in datetime format.

Here's what I have:

$sixty_days_past = strtotime("-60 days");

$earliest_time = date("Y-m-d H:i:s", $sixty_days_past);

$logs_result = mysql_query("SELECT id FROM df_logs WHERE date < '$earliest_time'");

    while($logs_row = mysql_fetch_array($logs_result)) { 

        $oldentry = $logs_row['id'];

        mysql_query("DELETE FROM df_logs WHERE id='$oldentry'");    

    }

What is wrong with this query?

1 Answer 1

1

Everything.

DELETE FROM `df_logs` WHERE `date` < DATE_ADD(NOW(),INTERVAL -60 DAY)

Done.


To elaborate:

  • You are going through PHP when MySQL is perfectly capable of doing the right calculations
  • You are not enclosing field names in backticks, which is a problem because date is a keyword.
  • You are deleting rows one at a time, which results in a potentially unbound number of queries, instead of deleting them all at once (such as with IN to list the IDs to delete)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.