I want to export some data from test_records table depend upon supplied from date and to date. I from and to date not supplied I want to export whole data. So how I can achieve that. Below is my code.

$from_date = strtotime($form_state['values']['fromdate']." 00:00:00");
$to_date   = strtotime($form_state['values']['todate']." 23:59:59"); 

$result = db_select('test_records', 'n')
      ->condition('submitted_time',  array($from_date, $to_date), 'BETWEEN')

I am using one condition that will compare submitted_time in database with supplied from and to dates. But When I pass nothing, it should get all the data from that table. Any suggestion will be appreciated.

1 Answer 1


I'm not sure if you can add if statement to a query but as you already have the values of $form_state['values']['fromdate'] and $form_state['values']['todate'] you can just add an if statement. If those two don't have values then execute a different query without the condition('submitted_time', array($from_date, $to_date), 'BETWEEN') condition.

Your Answer

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

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