I have a database where users enter a date, among other things, with a drop down calendar, the date format is in this format 21-NOV-2012 .
Is there a way to search the database with a date range ?
I currently search date using the following ::
sql ="SELECT * FROM ircb WHERE date LIKE '%$term1%' AND date LIKE '%$term2%' LIMIT $start_from, 15";
term1 is month and term 2 is year , this does not allow for date range within the month only for the month.
any help appreciated, thanks
I know this doesn't really solve your problem but I guess it's a testing (and you have access to the database) and will risk myself of getting flamed by telling you a better approach, as I will feel guilty if don't tell you what would be the correct way to do it:
You should have a Date type field in your database (I assume mysql) and store the whole date in that field, and mysql can search using that date (normally the standard date format would be YYYY-MM-DD) .
You just need to do:
SELECT * FROM TABLE WHERE date > 'your date';
or ........................... < 'your date';
or .................WHERE date BETWEEN 'date1' AND 'date2';
It will allow you to do those kind of operations in a much easier and human-readable way.
Also have a look at the datetime if you are interested, as you can do the same but with the time of that day also included in the same field! :D
Have a good look at the field types, as it's essential to have the database healthy and optimized.
date >= '$term2-$term1-01' AND date < DATE_ADD( '$term2-$term1-01', INTERVAL 1 MONTH)
I think this should work.
sql ="SELECT * FROM ircb WHERE date BETWEEN '$term1' AND '$term2' LIMIT $start_from, 15";
BETWEEN will let you fetch the range date, and you can delete those LIKE.
Related
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
I would like to select the next event from my table. the date of the event is stored as a VARCHAR in the format Y-m-d in a column called date.
But i am unsure how to compare VARCHARS/strings in sql. I tried the following but it gives me an event in the past.
$d = date("Y-m-d");
mysql_query("SELECT * FROM events WHERE date>$d ORDER BY date ASC LIMIT 1,1");
You haven't quoted your date string, so your query will be literally somethign like
... AND date > 2014-04-11 ORDER ...
Since there's no quotes, MySQL is free to interpret your date as a simple mathematical subtraction, and you end up doing
... AND date > 1999 ORDER ...
Try
... AND date > curdate() ...
instead. There's no point in having PHP generate a date and passing it into mysql, when mysql can generate that date perfectly well on its own.
As well, having PHP generate the date can lead to race conditions. E.g. PHP generates "today 11:59:59pm", but mysql actually executes as "tomorrow 00:00am". Maybe not relevant to you, but in banking "overnight run" code, this could cost someone literally millions of dollars.
SELECT * FROM events WHERE active=1 AND DATEDIFF(date, CURDATE()) >= 0 ORDER BY date ASC LIMIT 1,1;
This will select the next event inclusive of today's events. IF you do not want to include today's events, change >= to >
sqlfiddle: http://sqlfiddle.com/#!2/f205a3/9
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 have a php page which allows a user to sort pieces of information by several factors. A new requirement is to sort by "all items which have been registered in the last 15 days". I store my dates in the MYSQL table as mm/dd/yyyy.
The information is passed and picked up on the same page using the $_GET variable but I am unable for some reason to get the code to work. I have looked on numerous website but am unable to find a solution that works.
Ultimately, the script would work as follows:
select all persons who's KDATE is within 15 days of today's date (e.g., if today is 8/19/2010, everybody who registred from 8/04/2010 and on would appear).
My script so far (which does not work) is:
if (isset($_GET['date'])) {
$query = "SELECT *
FROM persons
WHERE DATE_SUB(CURDATE(),INTERVAL 15 DAY) <= KDATE
ORDER BY KDATE ASC";
}
Update 1:
KDATE IS TEXT - i apologize but the KDATE is stored as TEXT
Update 2:
The answer provided by Colin solved my issue. I will look into trying to convert the data into datetime format but am hoping the group can provide realistic benefits of doing so.
Thank you all again
First of all, it's a really bad idea to use VARCHAR instead of DATE if you want a collumn with dates only.
If you want to use a string as a date, you'll need to convert it with STR_TO_DATE() and you might wan't to use those instructions to correctly format your date.
This should do it:
SELECT *
FROM persons
WHERE DATE_SUB(CURDATE(),INTERVAL 15 DAY) <= STR_TO_DATE(KDATE, "%c/%d/%Y")
ORDER BY STR_TO_DATE(KDATE, "%c/%d/%Y") ASC
Because kdate is VARCHAR, you need to use STR_TO_DATE to change it to a DATETIME.
You need to fix kdate data that does not fit that pattern (mm/dd/yyyy) before running this:
SELECT *
FROM persons
WHERE DATE_SUB(CURDATE(),INTERVAL 15 DAY) <= STR_TO_DATE(KDATE, 'm/%d/%Y')
ORDER BY STR_TO_DATE(KDATE, 'm/%d/%Y') ASC
This means that an index on kdate is useless, because of having to change the data type.
Once it's a DATETIME, you can use DATE_FORMAT to change the format as you like.