0

I would like to create a query that filters records in a table using a date range.

  • The table has a "date" column that follows MM/DD/YYYY format.

I have this existing function that filters the records by "type" automatically, but how can I attach arguments to this function that uses a date range to only show records that fall within the range?

Say, for example, find a record that falls between 04/01/2015 and 04/30/2015.

public function getByType() {

    $query = $this->pdo->prepare("SELECT * FROM `" . $this->table . "` WHERE type='hod'");
    $query->execute();

      if ($query->rowCount() == 0) return null;

}

Thank you!

1
  • 2
    MySQL stores a DATE type as YYYY-mm-dd Commented Oct 21, 2015 at 14:40

1 Answer 1

3

You are storing dates with wrong data types. Storing dates as varchar string is like inviting evil to your application. You should always store dates with mysql native date data types date,datetime,timestamp etc. with the date as Y-m-d format

However in the current case you can use str_to_date function to get the job done, but in long run you should think about correcting these.

So here how it works

mysql> select str_to_date('04/01/2015','%m/%d/%Y') as d ;
+------------+
| d          |
+------------+
| 2015-04-01 |
+------------+

So the query you could use as

SELECT * FROM table_name 
WHERE 
type='hod' 
and str_to_date(date,'%m/%d/%Y') between str_to_date('04/01/2015','%m/%d/%Y') 
and str_to_date('04/30/2015','%m/%d/%Y') 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much! Worked like a charm. I will update my dates in the DB to work with MySQL date type.

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.