Checking dates in a database against UNIX time - php

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.

Related

Select mysql date range based on a VARCHAR Date

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

PHP Date and Time, getting the 1st, 2nd, 3rd, and 4th week in a month

I'm using ChartJS to build a few graphs for ticketing applications.
What I'm trying to do is query the MySQL database for # of tickets created for the 1st, 2nd, 4rd, and 4th week of the current month.
$month_num_tickets = array();
for ($x=0;$x<=30;$x=$x+6) {
$from = date("Y-m-d 00:00:00",strtotime('first day of this month +'.$x.' days', time()));
$to = date("Y-m-d 23:59:59",strtotime($from, time()));
$get = mysql_query("SELECT id FROM tickets WHERE date_created BETWEEN UNIX_TIMESTAMP('$from') AND UNIX_TIMESTAMP('$to') AND assigned_tech_uid='$uid'") or die(mysql_error());
$month_num_tickets[] = mysql_num_rows($get);
}
Not sure how to setup the loop...
You can get a nice tidy count in a single query like this:
SELECT
CEIL(DAYOFMONTH(FROM_UNIXTIME(date_created)) / 7) AS week_of_month,
COUNT(id) AS tickets_per_week
FROM tickets
WHERE YEAR(FROM_UNIXTIME(date_created)) = ?
AND MONTH(FROM_UNIXTIME(date_created)) = ?
GROUP BY `week_of_month`
ORDER BY `week_of_month` ASC
Note if you used native datetime or timestamp fileds, you could get rid of all of those FROM_UNIXTIME conversions. This is based on a "week" being the first 7 days of the month, not based on specific days of the week. If you wanted it based on fixed weeks (in terms of sunday through saturday or such) you could just use WEEK() function in the SELECT instead.
That might look like this:
SELECT
WEEK(FROM_UNIXTIME(date_created), 0) AS week_number,
COUNT(id) AS tickets_per_week
FROM tickets
WHERE YEAR(FROM_UNIXTIME(date_created)) = ?
AND MONTH(FROM_UNIXTIME(date_created)) = ?
GROUP BY `week_number`
ORDER BY `week_number` ASC
Here week_number would be a value between 0-53 and would not necessarily have any meaning for display other than as a means for aggregation. I am using mode 0 for WEEK() functoin as this specifies Sun-Sat week. You can look at the definitions here and determine what mode suits you the best: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_week
None of these queries are optimized because you won't be able to use an index on date_created . If you do get around to changing that column type to a datetime or timestamp, you would also perhaps want to change you WHERE condition to the slightly less easy to read, but more index friendly version like this:
WHERE date_created BETWEEN '2014-12-01 00:00:00' AND '2014-12-31 23:59:29'
I think this should work for you
SELECT YEARWEEK(date_created), MONTH(date_created), COUNT(*) FROM tickets
WHERE date_created BETWEEN UNIX_TIMESTAMP('$from') AND UNIX_TIMESTAMP('$to') AND
assigned_tech_uid='$uid'
GROUP BY YEARWEEK(date_created), MONTH(date_created)

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.

MySql timestamp query and comparison in monthly and weekly

i have a table where i enter entries for applicants. it has a column date_added where the type is timestamp and the default is current_timestamp. i want to make a weekly and monthly report but i can't decide what would be the best thing to do. i need an sql statement that return the number of entry like this..
switch($searchby){
case "monthly": $qry = "select * from tblapplicant where date_added > $month"; break;
case "weekly": $qry = "select * from tblapplicant where date_added > $week"; break;
}
$res = mysql_query($select);
$rec_count = mysql_num_rows($res);
echo "There are <font color='red' size='3'>".$rec_count."</font> matching records found.";
i know this is incorrect but this is all i can think at the moment.
another thing i want is, i want it to be the exact year and month report..
edit:
output should be:
There are 13 applicants for the whole month of June 2013. - or if weekly -
There are 3 applicants for the third quarter of July 2013.
I suggest the following approach. First, use your php code to determine the day that your search period begins, and the day after it ends. For example, if it's a monthtly report for September 2013, your start date would be 2013-09-01, and the end date would be 2013-10-01. Then you simply have one query.
where date_added >= $startdate
and date_added < $enddate
The major benefits of this approach are:
The time component of your timestamp field gets handled.
Your query will run reasonably quickly, especially if date_added is indexed.
It's easier to sort out programmnig logic with application code than with sql
You can write your query as a stored procedure to make it even faster.
This can be your sql statement
select * from tblapplicant where month(date_added) > $month
select * from tblapplicant where DAYOFWEEK(date_added) = X
You should replace X whith your weeek day 1 = Sunday, 2 = Monday, …, 7 = Saturday

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