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
Related
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
In my project , I am generating and storing the Bill (invoice).
The date of Bill is coming to the textbox from the javascript date picker(small pop-up calender) before saving.
The format of the date is : DD-MON-YYYY (18-JUN-2013).
I am using 'Text' data type for storing dates in MySql table.
I have done selecting of records(Previous Bills) from the table by given single date like. . .
$result = mysql_query("SELECT * FROM outward WHERE date='".$date."' ORDER BY billNo");
Now, what i want to do is:
To select records (Bills) between two dates.....
My exact Question is:
Is it possible to query mysql database with this settings or I have to make some changes to select records between 2 dates efficiently ?
How can i achieve this ?
P.s. - Is it effective to use
1. "SELECT * FROM outward WHERE date BETWEEN '" . $from_date . "' AND '" . $to_date . "' ORDER by id DESC"
Or
2. SELECT * FROM outward WHERE date > "15-JUN-2013" and date < "18-JUN-2013"
You could do it in a pure SQL way, but you are going to have to do a full table scan for each query.
select the_dates,
STR_TO_DATE(the_dates, '%d-%M-%Y') as converted
from testing
where STR_TO_DATE(the_dates, '%d-%M-%Y') between '2013-06-20' and '2013-06-23'
Link to SQLFiddle
You should use strtotime PHP function to convert string date to UNIX timestamp format and change MySQL data type for date field to TIMESTAMP.
Than you can do effective queries with > and <.
If it's a DATE column, you can get all dates between 15 June 2013 and 18 June 2013 (inclusive) using this:
WHERE date BETWEEN '2013-06-15' AND '2013-06-18'
If it's a DATETIME column, do this instead:
WHERE date >= '2013-06-15' AND date < '2013-06-19'
If the date column is indexed, this approach will make sure the indexes are available for optimization. If it isn't indexed, the approach is just as fast as the many other ways you can do this.
Addendum: Just saw the "storing as text" amidst all the other shouted info. Note that this answer applies only if the type is DATE or DATETIME. I'll leave it up because the best answer is to change the column's data type and then use this or one of the other suggested options.
I am using 'Text' data type for storing dates in MySql table.
That's a problem. You should store dates as date or datetime data type in MySQL. If you don't care about the time part, date should be sufficient.
If you change your data type to date, then doing:
select x,y,z from table a where a.datecolumn between #startdate and #enddate
Should work fine.
If you use a text data type, you would have to cast the column to a date column and then apply your date selection range which is going to be slower due to the cast.
Always store data in the data type that matches its kind. If a date then a date column, if it's text then text or varchar, etc. The presentation layer of your app can worry about the format in which this data is presented to the user.
You said you were using a TEXT column to store the dates. That's an extremely bad idea. If you switch to a DATE or a DATETIME, then this becomes trivial.
Since you are storing it as text but you want SQL to parse it as a DATE SQL doesn't understand in the first place.
In your example SQL will use TEXT comparison rules. So 15-April < 15-Mar > 15-DEC
If you are storing dates in an SQL database you should be storing it as a Date and not as TEXT.
I have a MySQL database. In a couple of tables, the information that gets stored needs to be retrievable by week. So, I want to be able to do a SELECT FROM *database* WHERE week = *week*. The problem that I have is that the week part is stored as a unix timestamp (to allow for more versatilty like getting the date and time, just time, etc...).
So the question: How can I retrieve this record WHERE date = *date* when the stored date is a unix timestamp and date I'm matching it against is not?
If my question is too confusing and something needs to be rephrased or said in a clearer manner please comment and let me know.
MySQL has a built-in WEEK() method for handling dates: MySQL WEEK() Reference
Unfortunately however, MySQL's WEEK() method only supports DATE datatypes rather than a UNIX TIMESTAMP. Therefore, we must first convert the timestamp to a date so we can then pass that date to the WEEK() method:
SELECT
*
FROM
my_table
WHERE
WEEK(
DATE_FORMAT(
FROM_UNIXTIME('my_unix_timestamp_col'),
'%e %b %Y'
)
) = 51
If you have a column which is the DATE data-type, the query can be simplified (and can also use indexes):
SELECT * FROM my_table WHERE WEEK(my_date_col) = 51
I am working on a campsite management system and have been trying to figure out date selection query.
$sdate is the starting date of the reservation
$edate is the end date of the reservation
I am simply trying to find the sites that are not currently reserved between the dates.
Right now it works fairly well, except in the case where someone wants to reserve the same day that someone is leaving, it is considered taken because someone is "in" that spot, but will be leaving that day so it shouldn't show up.
Date format is mm/dd/yyyy
Format in the database is not set to date, is set to varchar with the same format.
$searchSite= $wpdb->get_results("SELECT *
FROM wp_campground_sites
WHERE wp_campground_sites.id
NOT IN
(
SELECT wp_campground_sites.id
FROM wp_campground_sites
JOIN wp_campground_reservations
ON wp_campground_sites.id = wp_campground_reservations.site_id
WHERE
(
'$edate' between reservations.sdate and reservations.edate
OR
'$sdate' between reservations.sdate and reservations.edate
OR
reservations.sdate between '$sdate' and '$edate'
)
");
you have to change your varchar string to date format and compare like
select date_format(str_to_date('12/31/2011', '%m/%d/%Y'), '%Y%m');
because you are going to compare string in with date result will not display until you use date_formate function to convert varchar datatype to actual date format.
I have two fields in the DB stating the start-time and end-time, and another field that may or may be not set that is called 'date'.
Upon SELECT, I need to know if I am in or out of the time range, and if the date is set if I am in the time range only if the date is today.
What is the best way to do that in PHP ?
Thanks!
My original answer was not answering your question at all I realised. Hopefully this will.
$query = "SELECT IF(".date('H-m-s')." BETWEEN start-time AND end-time,
'inRange', 'notInRange') WHERE `date` == CURRENT_DATE OR `date` IS NULL";
If date('H-m-s') from PHP is in the range it will return the string "inRange" otherwise it will return the string "notInRange" and will match it on the records in your db where date is either NULL, or the current date.
You could also make the SQL statement like this:
SELECT IF(TIME(CURRENT_TIMESTAMP) BETWEEN start-time AND end-time, 'inRange',
'notInRange') WHERE myDate == CURRENT_DATE OR myDate IS NULL;
Upon SELECT, I need to know if I am in or out of the time range
SELECT (NOW() BETWEEN date_min AND date_max) is_happening_now
FROM your_table
is_happening_now contains a boolean containing true if NOW() is between date_min and date_max. Obviously, that would create a separate column that you might not need, you can put the condition in the WHERE clause if necessary.
if the date is set if I am in the time range only if the date is today.
I didn't really understand this part, but you can extract the date from a DATETIME with the DATE function (for example : current_date = DATE(some_date)