Select mysql date range based on a VARCHAR Date - php

What I am up to here is fetching some data from mysql table within a week from today. My only challange is that Dates are stored in VARCHAR format D M d Y.
My table stored Date example: Wed Jul 03 2016
My Code is:
$result = mysqli_query($con," SELECT * FROM `BIMTECH_academy_2016_classes` WHERE STR_TO_DATE(Date, '%D %M %d %Y') > DATE_SUB(NOW(), INTERVAL 1 WEEK) ORDER BY Date,From DESC; ");
while($row = mysqli_fetch_array($result))
{
echo $row['ClassNumber'];
echo $row['CourseName'];
echo $row['Date'];
echo $row['From'];
echo $row['To'];
}

That's... well, a bit sad. Dates should be stored as proper data type because you can query the data without too much overhead. If there's any chance, please do convert those dates to valid date format and change the column type to date or datetime.
In the meantime, you can use MySQL's STR_TO_DATE() function, but since it would be used in WHERE part of the query, then MySQL will always scan the entire table, then internally convert all strings to dates, and only then compare with what you need. If there's a lot of data stored in a table, that can be really slow. Indexing the column won't help either, since MySQL has to fetch and convert all columns anyway before it's able to perform the comparison.

example:
just relace #date with your column name and you should get the date returned in format you want.
SET #date = "Sun Jul 10 2016";
SELECT DATE_FORMAT(STR_TO_DATE(#date,"%a %b %d %Y"),"%Y-%m-%d") as formatted_date
more details: DATE_FORMAT,STR_TO_DATE

Related

How to query a table based on timestamp with date in dd-mm-yyyy format

I have a table containing a field "created_at" whose Data Type is timestamp. I donot want to change it to DATE.
Can i query this table to fetch all rows of a day in format dd-mm-yyyy.
Note:
One approach I tried is:
a) Take Date in yyyy-mm-dd concatenate with 00:00:00
b) Take next date in yyyy-mm-dd concatenate with 00:00:00
and use below query to get all records of that day:
SELECT *
FROM news
WHERE created>='2016-12-13 00:00:00'AND
created < '2016-12-14 00:00:00'
Is this a good solution to my problem. Any better approach for this problem.
You can use the MySQL cast() function.
SELECT
*
FROM news
WHERE CAST(created_at AS DATE) = '2016-12-13'
This will discard the time component of your timestamp and do the comparison on only the date.
Reference: http://dev.mysql.com/doc/refman/5.7/en/cast-functions.html
If you don't want to change column datatype then you can go with this code
$startDate = strtotime( '2016-12-13' ); // it will convert date to timestamp format.
$endDate = strtotime( '2016-12-15');
$query = "SELECT * FROM news WHERE created >= '$startDate' AND created < '$endDate'";

Checking dates in a database against UNIX time

I have a table showing flights. The dataset is automatically imported so I would prefer not altering data in the database.
The set has a start and end date for a flight. The columns are called "start" and "end", and contains for example the start date "4-Nov-15" and end date "17-Dec-15".
How can I build a query to check if a row is within these two timeframes?
$currenttime = time();
mysql_select_db("wifva");
$result = mysql_query("SELECT * FROM flights WHERE start <= '$currenttime' && end >= '$currenttime' ORDER BY deptime");
while($row = mysql_fetch_array($result))
{
?>
<tr class="hover" style="text-align: left;">
<td class="border_bottom"><?php echo $row['deptime'];?>z</td>
<td class="border_bottom"><?php echo $row['callsign'];?></td>
The above code does show data in my table, but doesn't output the correct information (assuming that php/sql doesn't automatically recognize date format etc).
Any help is appreciated.
I believe you can use "UNIX_TIMESTAMP" in your query to do that. It's use is described well here:
SELECT UNIX_TIMESTAMP(STR_TO_DATE('Apr 15 2012 12:00AM', '%M %d %Y %h:%i%p'))
OR
SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(STR_TO_DATE('Apr 15 2012 12:00AM', '%M %d %Y %h:%i%p'))
I found this in this SO answer by user query_master (https://stackoverflow.com/users/1352125/query-master): MySQL convert datetime to Unix timestamp
You should be able to adapt it to fit your needs, though I haven't tested it with your particular date format that's currently in the DB.

Using Date functions to pull records from database

I'm truly stumped on something - I have a table in my database with a column called 'today' that has Date and Time records. The column has entries that look like this:
October 25, 2014, 4:58 am
October 25, 2014, 4:36 am
I'm having trouble pulling the rows by date; I think the time stamp is messing with the MySQL query. And I need an SQL query to pull any records where the variable $today matches the date information in the column 'today'. This doesn't work:
$today = date("F j, Y"); // looks like this: October 25, 2014
$result = mysqli_query($link,"SELECT * FROM records WHERE today = $today"); // 'today' represents the column in the table
while($row = mysqli_fetch_array($result)) {
echo var_dump($row);
}
I just get an empty result, I think due to the time stamp. Can someone advise on a better MySQL query that will only grab the rows where $today matches the date in the 'today' column?
Although storing the date and time as string in varchar is not really a good idea, you could still alter your query to match string containing the current date with a LIKE statement:
$result = mysqli_query($link,"SELECT * FROM records WHERE today LIKE '$today%'");
That is just to get your current setup working as a temporary fix but i highly suggest you take a look at datetime and timestamp or similar date types if this is a serious project and not just playing around. with programming.
UPDATE
With a datetime you could get the dates which are the same as today with:
SELECT * FROM `records` WHERE `today` = CURDATE();
with a timestamp you would need to pass it as date so your query would be:
SELECT * FROM `records` WHERE date(`today`) = CURDATE();
You can just use the MySQL date functions:
SELECT *
FROM records
WHERE today = CURRENT_DATE;
If there is a time component on the today column, then the best structure is:
SELECT *
FROM records
WHERE today >= CURRENT_DATE and today < date_add(CURRENT_DATE, interval 1 day)
It's obvious that both dates are not equal. Both dates are treated like text values and are not equal. You need to convert the column containing date in your MySQL query as such:
$result = mysqli_query($link,"SELECT * FROM records WHERE DATE_FORMAT(today, '%F %j, %Y') = $today");
Note that you have to change your column to store values of the type of DATE. Or just use queries as proposed in other answers.

getting first 5 digits of a database stored number in the query

I'm working with a table and there is field in my table which stores raw time() function value as date.
I want to get rows with today date from this table .
So i figure out when time() func returns a 10 digit number like 1316352184 the first 5 digits are for year , month , day which i need for getting today's date and the rest is for hour minute Second which i dont need
So i get today without hour and... like
$t = time();
$t = $t /100000;
$today =(int)$t;
Now i need to get rows with today date from the table but i'm not sure how to do that.
How can i get first 5 digits of stored date in database in my query to compare it with $date?
Something like this:
$sql = "SELECT * FROM TABLE WHERE ((int)date/100000) as date = $today ;
select * from table
where from_unixtime(unix_timestamp_field,'%Y-%m-%d') = curdate()
Why you don't use:
$sql = "SELECT * FROM TABLE WHERE date(date) = date(NOW());
What you have is a UNIX timestamp. The number of seconds since January 1st, 1970.
You can use date() and mktime() to work out what todays timestamp is, then do date > the timestamp. If that make sense.
Sounds like you should use the DATETIME or TIMESTAMP data type for your column so you can use MySQL's date functions.

Getting any rows which were added before a certain date

Would this be possible? I've used this to insert the date into a field called "date":
$date=date("m/d/y");
$sql="INSERT INTO pool (date) VALUES('$date' )";
$result=mysql_query($sql);
I've used this statement to get the date a week ago:
$variable = date('d-m-y', strtotime('-1 week'));
So how would I SELECT any rows which were added last week?
Instead of storing your dates as m/d/y, you should store them as Y-m-d :
$date=date("Y-m-d");
$sql="INSERT INTO pool (date) VALUES('$date' )";
In the database, you dates will then look like 2011-04-09.
That format is much easier to work with : alphabetical comparisons will work.
Which means that searching for rows that are older than a certain date would become something like this :
$variable = date('Y-m-d', strtotime('-1 week'));
$query = "select * from pool where date < '$variable'";
Also note that instead of working with a date field which is a varchar (or an equivalent) in your database, you could use a DATE column -- which would allow to to work with date and time functions in MySQL.
If the date field is a proper date type you can do < or > in your sql query. For example -
SELECT * FROM table WHERE date > '$date'
If you want everything from 1 week ago to now you can do something like the above or
SELECT * FROM table WHERE date BETWEEN '$date' AND NOW()

Categories