Select next event - php

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

Related

Getting wrong answer with mysql date query

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

Search mysql database for date range

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.

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

PHP/MySQL Date Search

My script works fine for all sales but skips all sales on the 15th.
The MySQL rows for the period look like this:
ID: 10 START: 2010-12-01 END: 2010-12-15
The MySQL rows for the sales look like this:
DATE: 2010-12-15 20:40:26
$period_info=mysql_fetch_array(mysql_query("SELECT start,end FROM period WHERE id='$period' LIMIT 1"));
$start=$period_info["start"];
$end=$period_info["end"];
$total_sales=mysql_num_rows(mysql_query("SELECT * FROM sales WHERE seller='$seller' AND date BETWEEN '$start' AND '$end'"));
And ideas?
This is because MySQL uses 00:00:00 as the time for the DATE type. I think you can use:
"SELECT * FROM sales WHERE seller='$seller' AND (CAST date AS DATE) BETWEEN '$start' AND '$end'".
Only compare the date part of the datetime, and ignore the time part:
WHERE DATE(`date`) BETWEEN '$start' AND '$end'
For best results when using BETWEEN with date or time values, use CAST() to explicitly convert the values to the desired data type. Examples: If you compare a DATETIME to two DATE values, convert the DATE values to DATETIME values. If you use a string constant such as '2001-1-1' in a comparison to a DATE, cast the string to a DATE.

How to sort by Date from MYSQL using PHP

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.

Categories