Getting wrong answer with mysql date query - php

Here is my table
I am executing a query that give me result of fields whose item_valid_from must be greater than today's date and item_valid_to must be less than today.
My query is
select *
from tbl1
where item_valid_from >= CurDate()
and item_valid_to < CurDate()
Any Solution?

I would advise you to change item_valid_* field formats to DATE field format. You will save you a lot of trouble in the future.
But ok, if you don't want to do that, then you can use STR_TO_DATE() function:
SELECT *
FROM `table`
WHERE CURDATE() BETWEEN STR_TO_DATE(`from_field`, '%d-%m-%Y') AND STR_TO_DATE(`to_field`, '%d-%m-%Y')
demo

Assuming the datatype item_valid_from and item_valid_to is DATE, TIMESTAMP, etc, then you have your operators backwards. Think of the time as seconds since 1970, since this is how it is stored in unix time. That means that item_valid_from is going to be smaller than item_valid_to, and you want it to display when today is somewhere between them. You want the item_valid_from to be less than or equal to now, and the item_valid_to to be greater than now (not in the past).
SELECT *
FROM tbl1
WHERE item_valid_from <= CURDATE() AND item_valid_to > CURDATE()
See this SQL Fiddle for an example, only 2-4 are valid and show up in the results being valid from a date in the past and expiring on a date in the future.

You have to use following query which change current date format then compare date and fetch result :
SELECT *
FROM tbl1
WHERE date_format(item_valid_from,'%d-%m-%Y') >= date_format(CurDate( ),'%d-%m-%Y')
AND date_format(item_valid_to,'%d-%m-%Y') < date_format(CurDate( ),'%d-%m-%Y')
Please Check this :http://sqlfiddle.com/#!2/561d0/2

Related

Compare date and datetime

I want to compare a datetime from sql and the todays date.
The datetime in sql is for example 2015/05/09 12:00:00 and the current date is 2015/05/09. I want to compare these things if they are equal, but for the whole day so the time is a problem. I have the following query.
$q1="SELECT reservations.reservation_id, reservations.room_id, room.room_rate, reservations.arrival_date, reservations.departure_date,
meals.meal_rate, room.room_rate, roomtype.max_persons,
CONCAT(clients.first_name,' ',clients.last_name)as name
FROM reservations, clients, meals, room, roomtype
WHERE reservations.room_id=room.room_id AND reservations.client_id=clients.client_id AND room.roomtype_id=roomtype.roomtype_id
AND reservations.meals=meals.meal_id AND reservations.arrival_date=CURDATE()
GROUP BY reservation_id
";
reservations.arrival_date=CURDATE() this is equal only at 12:00:00 o'clock. i want that to be equal for the whole day.Actually i want to compare if these two dates are equal without time but my database must be datetime with the time...
does anyone has an idea?
thanx in advance
You should learn to use standard join syntax. Simple rule: Never use commas in the from clause.
The answer to your question is either the date() function (or something similar):
where date(reservations.arrival_date) = CURDATE()
Or an inequality:
where (reservations.arrival_date >= CURDATE() and
reservations.arrival_date < date_add(CURDATE(), interval 1 day)
)
The second is actually preferred because it can make use of an index on reservations(arrival_date).

How to filter MySQL dates?

I'm trying to do a SELECT * FROM but only items that are less than 30 days old. Here is my select code:
SELECT * FROM `{$table_name33}` WHERE `type`='wpst-requiredinfo' ORDER BY `foreignkey` ASC;
However, my problem is that I can't figure out how to add WHERE AND last_updated is less than 30 days.
I'm not exactly sure how to write the query, but the date is showing up like this: 1428412603 in the table column, it doesn't look much like a date to me. I don't know where to start.
Try this where clause:
WHERE `type`='wpst-requiredinfo' and
last_updated >= date_sub(now(), interval 30 day)
EDIT:
Your date seems to be in Unix time format.
WHERE `type`='wpst-requiredinfo' and
last_updated >= unixtime_timestamp() - 30*24*60*60
Note: this puts all the functions on the current time. In particular, it does not use FROM_UNIXTIME(last_updated). This ensures that an index can be used for this part of the query. The best index would be on (type, last_updated).

MySQL query: Date > Date not working

Hi there please help me if you can. Here is my senario:
I have a MySQL database with a column that holds a date in the form of a varchar. The format of the date is the following 29/05/2014 (i.e. d/m/Y).
I'm trying to compare the value of this column with todays date and return any rows where the date is earlier than todays date.
I'm using a php variable to store todays as follows:
$date = date("d/m/Y");
Here is my SQL query:
SELECT * FROM patients WHERE last_seen < '$date'
What gets returned
So what is returned is very unusual (to me). All records where the last_seen "day" is less than todays "day". It seems to be overlooking the month and year. So in other words if I last_seen = "30/05/2014" and todays date is "29/05/2014" this record is still returned.
Does anyone have any ideas what I might be doing wrong here?
Thanks
You really, really shouldn't store dates in a varchar field - use date or datetime or timestamp data type.
That said, sometimes you don't have control over the database and you have to deal with somebody else's bad design decision. In this case, to compare dates, convert the varchar strings to dates and compare them that way. So, in your case, you can have something like this:
$date = date("d/m/Y");
and then
SELECT * FROM patients WHERE str_to_date('last_seen', '%d/%m/%Y') < str_to_date('$date', '%d/%m/%Y')
or simpler
SELECT * FROM patients WHERE date(last_seen) < current_date
This way you are actually comparing dates and not strings containing dates. Naturally, this assumes that all dates are stored in the same format.
EDIT: I just tested the last option - and, apparently, date('30/05/2014') returns NULL on my system (mysql 5.5 on linux), hence I suggest the best way is
SELECT * FROM patients WHERE str_to_date('last_seen', '%d/%m/%Y') < current_date
You need to store your date as DATE or DATETIME in your database.
Then you can use:
SELECT * FROM patients WHERE DATE(last_seen) < CURRENT_DATE

Time date comparsion in PHP

I have a table in my database that stores user input as a start date and end date after that, my users will have to select a time range and I have to display those records in the table that are within this time range?
Tried stritotime(); and many other unctions but somehow I can't get the right results..
Any possible solution would be appreciated.
Thank you!
May be with:
SELECT count(*) FROM `table`
where
created_at>='2011-03-17 06:42:10' and created_at<='2011-03-17 06:42:50';
or use between:
SELECT count(*) FROM `table`
where
created_at between '2011-03-17 06:42:10' and '2011-03-17 06:42:50';
it depends on your record what u want to display because i didnt see your table and an exemple what you you really to do so just change count(*) and get whatrecords you want.
EDIT:
if the users will select a range of time then they will be variables
then it will be something like that
SELECT records FROM `table`
where
created_at >= '".$var_start_time."' and ended_at <= '".$var_end_time."';
you can use in mysql query BETWEEN ... AND ... comparasion operator
http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#operator_between
You can simply do this in your SQL, which is the recommended approach. If you have these start and end times stored in your database table as native DateTime types, for example, you can use your DBMS' Date functions to select the range as a UNIX timestamp (if that's what what you want).
SELECT UNIX_TIMESTAMP(`start_time`), UNIX_TIMESTAMP(`end_time`) FROM `table` WHERE `start_time` > INTERVAL -1 DAY AND `end_time` < NOW();
That's one example (assuming you're using MySQL) where you select all rows in the table where the column start_time is within the past 24 hours and the end_time column is up to the current server time.
To get the formatted date and then do the conversion to a UNIX time-stamp in PHP use:
SELECT `start_time`, `end_time` FROM `table` WHERE `start_time` > INTERVAL -1 DAY AND `end_time` < NOW();
and then in PHP you can do:
$result['start_time'] = strtotime($result['start_time']);
$result['end_time'] = strtotime($result['end_time']);
Keep in mind that strtotime expects the formatted date to comply with PHP's date parsing rules found here.
P.S: The function in PHP you're looking for is strtotime not stritotime.

Sort SQL result by date greater than today (d-M-Y)

In my sql query I output dates in chronological order.
The dates in my database are stored in d-M-Y format.
What I want to do is sort the results by dates equal to or greater than today to be output first.
In my query I have this sort in my query
...From $db ORDER BY STR_TO_DATE(sortdate, '%d-%M-%Y') ASC
Can anyone tell me if I can do a comparison on todays date as each record is output from the db?
This will give me todays date
$todaysdate = date("d-M-Y", time());
but can anyone tell me if I can build that into my query?
Thanks in advance.
check mysql DATEDIFF in combination with CURRENT_DATE ==>
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_current-date
My guess is that you saved the date in a VARCHAR column. Please don't do that, you make it very complicated for yourself when you want to do stuff (like this) with the date. I'd suggest that you convert the column to a DATE field and then just use:
SELECT * FROM my_table WHERE my_date_field >= CURDATE()
And if you want to output the date in the d-m-Y format, you can use DATE_FORMAT()
You really should be storing the dates in a dateTime format. That will make it much easier to do all sorts of orders, comparisons and plenty of other things. You could for example, then use the mysql now() function to only get the results you need?
...From $db where sortDate>=now() ORDER BYsortdate ASC
Assuming sortdate is datetime field, in order to display dates equal to or greater than today first,could use UNION.
SELECT * FROM my_table WHERE sortdate>= CURDATE()
UNION
SELECT * FROM my_table WHERE sortdate< CURDATE()
You can use WHERE sortdate >= $todaysdate
Just put this condition in where like date_column >= curdate()/$todaysdate
thanks

Categories