Jump to content

How to select records between 2 dates stored as varchar using prepared statement?


angel1987
Go to solution Solved by cataiin,

Recommended Posts

I have been searching on internet for quite a while now for the query, tried many but none work, so i am resorting to asking myself.

 

I have a table column with type varchar that stores date in format mm-dd-yyyy. I need to fetch all records from this table with the dates within next 4 days (between today and next 4 days).

 

Also, i am using mysqli prepared statements to fetch this record.

 

Below is the query which i tried, it works but not accurately.

if ($stmt = $mysqli->prepare("SELECT names FROM members WHERE birthdate - INTERVAL 4 DAY > NOW() AND gender = ?")) {

The above query displays records with dates after 4 days from today. I tried changing combinations for + - > and < like i had no idea what i was doing but each combination gave funny results.

 

Has anyone tried this or knows how to do it? Please help me with this query, thanks in advance for your help.

Link to comment
Share on other sites

Date arithmetic (and all other MySQL datetime functions, comparisons and sorting) will not work with dates in mm-dd-yyyy format.

 

Don't use varchar for dates, use DATE type fields (format YYYY-MM-DD).

 

Also, if working with just dates, use CURDATE() and not NOW() as the latter contains time element. Unless it is exactly midnight 2013-09-08 doesn't = NOW()

 

You can convert varchar dates to DATE using STR_TO_DATE() but then you need it in every date calculation.

 

 

edit:

If you date is actual birthdate, including year of birth, then it won't be in the range of the next 4 days

Edited by Barand
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.