简体   繁体   中英

Selecting data from database based on date

hope you fine and well,

i have a table that contains persons information and i have a registration date column in the table, i want to to fetch the registered people in specific date.

to be more specific i want to enter some date in html input then to select from database based on this date.

i tried two solutions but they failed actually:

  1. by entering the full date : this will work just with full date, for example if i entered 2016-1-1 i will get the results of this date, but if i want to return all the people who registered in 2016-1 or 2016 my query will fail since these values are not equal the dates in the table !

  2. using regular expression, its okay but it will fail again ! if i entered 2016-1 for example , the query will return the results of 2016-11 also !

so any ideas ?! or any better regular expressions ?!

regards.

Best solution would be to do it in the query, in my opinion at least.

So you want all users from 2016?

SELECT * FROM `users` WHERE year(`date_field`) = '2016'; 
// Where 'date_field' is the name of your date field

Or 2016/01 would be:

SELECT * FROM `users` WHERE year_month(`date_field`) = '2016-01'; 
// Where 'date_field' is the name of your date field#

Or you could use this for 2016/01:

SELECT * FROM `users` WHERE year(`date_field`) = '2016' AND month(`date_field`) = '01'; 
// Where 'date_field' is the name of your date field

For a full list of MySql date functions check out the documentation .

I would like to add that you can also query for results between certain dates.

What i often end up doing is:

// For a certain month or period
SELECT *
FROM users
WHERE date_field >= '2016-01-01'
AND date_field <= '2016-02-01';

// For a whole year
SELECT *
FROM users
WHERE date_field >= '2016-01-01';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM