0

I have a table with a date column and I'd like to delete rows that are older than 5 minutes than "now".

I tried with db_delete conditions but it doesn't work.

I tried this query:

$deleteOldRows = db_delete('reserves') 
    ->condition('entityId', -1) 
    ->condition('dataReg + 5 MINUTES', 'NOW()') 
    ->execute();
5
  • Could you post the code that you have tried here so we can review it? Commented May 23, 2017 at 17:24
  • I tried this query: $deleteOldRows = db_delete('reserves') ->condition('entityId', -1) ->condition('dataReg + 5 MINUTES', 'NOW()') ->execute();
    – SmurfXXX
    Commented May 24, 2017 at 7:08
  • Could you edit the question and include that? Commented May 24, 2017 at 7:25
  • Done it, sorry!
    – SmurfXXX
    Commented May 24, 2017 at 12:46
  • No problem, now we have a proper question :) Commented May 24, 2017 at 13:19

1 Answer 1

1

The problem is with the condition syntax; it looks like below and performs a binary comparison:

$query->condition($field, $value = NULL, $operator = '=')

There are several issues, there is no field dataReg + 5 MINUTES and it likely won't have the literal value NOW() either. Besides, since you omitted the operator, the query would (if it had worked) only select items that are exactly 5 minutes old.

You are looking for a way to execute SQL in the query instead, which is provided by the where clause:

$query->where($snippet, $args = array())

In your case, it would probably look like this:

$deleteOldRows = db_delete('reserves') 
  ->condition('entityId', -1) 
  ->where('`dataReg` + 5 MINUTES < :time', array(':time' => 'NOW()')) 
  ->execute();

You can find some good information on conditional clauses here: https://www.drupal.org/docs/7/api/database-api/dynamic-queries/conditional-clauses

UPDATE

It appears I was wrong and this can be done with conditions after all, you should just reverse the logic. Rather than adding 5 minutes to the date, subtract 5 minutes from now.

$query->condition('dataReg', $adjusted_date, '<=')

Where $adjusted_date for timestamps would be time() - (5*60). And for DATE types something like date('Y-m-t H:i:s', time() - (5*60)).

3
  • Thank you for your reply, I tried the code you posted but it returns a syntax error, I looked for the documentation but I can't understand how to correctly write the condition 'dataReg + 5 MINUTES'
    – SmurfXXX
    Commented May 24, 2017 at 15:14
  • Please see my updated answer Commented May 24, 2017 at 15:26
  • 1
    Damn, I didn't think to reverse the logic, you're right! Thank you!!!
    – SmurfXXX
    Commented May 25, 2017 at 13:10

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.