Select MySQL row where column is closest to current date - php

I have a database with a bunch of rows. One of the columns is "date" which has a date for each row in the format: MM/DD/YYYY H:MM PM/AM
How can I write PHP that selects the row where the date is the most recent date that has passed. Meaning if you have a date of tomorrow, a date of today, and a date of yesterday, it picks the row where the date is of yesterday.
I've already connected to the database:
mysql_connect('localhost','username','pass');
mysql_select_db('db_name');
How do I write a query to grab this?

I would do the filtering in SQL rather than PHP, using a variation of the following query:
SELECT *
FROM myTable
WHERE theDate < CURDATE()
ORDER BY theDate DESC
LIMIT 1
This selects all the rows in the past (theDate < CURDATE()), sorts them in reverse chronological order (ORDER BY theDate DESC), then takes the first record (LIMIT 1).

When you query the database, ORDER BY date DESC LIMIT 1
This will only return the most recent result, and thus the result that is closest to the current date. (This only works if you don't put entries that are dated in the future)

Related

MySQL Query For Latest Record Before a Date

I have a MySQL database which stores LogID, unix timestamp, temperature, humidity and light level. I am trying to get a query that extracts the last record before a set date & time. My data is as follows:
|69511|2017-04-24 19:53:23|19.8|52.7|1.76
|69512|2017-04-24 20:07:57|20|53.8|1.86
|69513|2017-04-24 20:12:00|20.1|54.9|1.07
|69514|2017-04-24 20:29:58|20.2|53.8|1.95
So if the required date was 2017-04-24 20:10:00 the query would return the record:
|69512|2017-04-24 20:07:57|20|53.8|1.86
as the first record preceding 2017-04-24 20:10:00.
Can anyone help? Thanks.
Use a WHERE clause to limit your search to records before the date in question, then sort in descending order by the timestamp (sorting by ID will probably work as well) and take the first record with LIMIT 1.
SELECT * FROM your_table
WHERE ts_column < '2017-04-24 20:10:00'
ORDER BY ts_column DESC LIMIT 1
I improvised the name of your table & timestamp column, but this should give you the general idea.
Perhaps try:
SELECT * FROM {tablename} WHERE {timestamp column} < '2017-04-24 20:10:00' LIMIT 1
EDIT: add 'order by unix_timestamp desc'
Filter the records in where clause using the timestamp. Sort it by descending order and get the top 1 record using limit.
select * from table_name
where unix_timestamp < '2017-04-24 20:10:00'
order by unix_timestamp desc
limit 1

Order mysql query by date and time which are separate columns

I wish to order my mySQL query by date and time as if they were a combine column (datetime) however they are a separate column (Date and Time). I need to be able to display all the records from a table that are after the current time (using Date("")).
If we assume you have table t with structure:
id | date | time
Then to order by date and time you do:
SELECT * FROM t ORDER BY date,time
To select everything that's newer than the current time do:
SELECT * FROM T WHERE date > CURDATE() OR (date = CURDATE() AND time > CURTIME())
There's an alternative way to do the second one which is based on Creating DATETIME from DATE and TIME so you can refer to that if you need to.
You can combine the above and do a :
SELECT * FROM T WHERE date > CURDATE() OR (date = CURDATE() AND time > CURTIME()) ORDER BY date,time

Php mysql get the nearest-latest record if a record is not exist (datetime based)

Trying to get my head around, If I select a record such as WHERE item_id='$item_id' AND date(datetime)='2012-06-25' and if that record does not exist so I want to get the nearest-latest record after that date. How can I achieve that in a query?
All I can think of the only way right now is if num_of_rows is 0 then I add 3 days period ahead to that day and search again and get the DESC datetime LIMIT 1 (in case there are multiple rows). But who knows I can do it with just a query.
The record could have multiple rows in one day. So if a particular date has no record, how to get the next nearest available data given the same $item_id?
SELECT *
FROM table
WHERE field <= '2012-06-25'
ORDER BY field DESC
LIMIT 1
I think this is what you are looking for:
SELECT *
FROM my_table
WHERE datetime BETWEEN '2012-06-25 00:00:00' AND
DATE_ADD('2012-06-25 00:00:00', INTERVAL 3 DAY)
ORDER BY datetime ASC
LIMIT 1;
also create index on field datetime for faster performance.
This will bring back the item closest to the date that you enter into the query. It won't however look for before or after, just find the closest date to what you enter in.
select
min(abs(DATEDIFF(date(datetime),'2012-06-25'))) as minDiff
,yourID
from table1
group by yourID
order by 1 asc;

MYSQL retrieve results where date = next weekend

Currently I have two tables and the following sql statement which correctly retrieves the items in the events table ordered by their dates in the event_dates table:
SELECT * FROM events, event_dates
WHERE events.id=event_dates.event_id
AND events.preview=0 AND event_dates.start_date>=now()
ORDER BY event_dates.start_date ASC,event_dates.start_time ASC LIMIT 3
Now I want to add an extra AND to make sure only the events on the next weekend are set. The date column is in a standard mysql date format (YYYY-MM-DD). Got stuck on this bit. Cheers.
Use PHP strtotime() to get the start and end timestamp of the weekend:
$we_start=strtotime('next saturday');
$we_end=strtotime('next monday')-1;
Then do a sql query to search for timestamps BETWEEN them.
select * from mytable where UNIX_TIMESTAMP(mydatefield) BETWEEN $we_start AND $we_end
Hope that helps.

Selecting the next date in MySQL

I have a list of dates in a table in a MySQL database (the dates when a charity bookstall is to be held), which I want to display on a page. On one page I'm displaying the date of the next stall, and on another the dates of the stall in the next month. (Currently I'm using an unordered HTML list and selecting the dates with PHP, but it's a bit messy, and I also want to tie in the dates with the fundraising totals that are stored in the database).
I want to put the dates in a database though so that I can tie in the dates with the fundraising totals for each week. I'm thinking that once I can identify the date with the nearest up-coming date that I can use 'LIMIT 1' to select the next week's date for display, and 'LIMIT 4' say for where I need to display the dates for the next month, but what I can't figure out is how to identify the record with the nearest up-coming date - identifying the current date and then selecting the nearest date...I have a feeling there's probably one of the MySQL date functions that can be persuaded to help out in this, but can't figure out exactly how.
Any ideas on how I can do this?
If I understand correctly, you can just pick up next four dates that are after today.
In MySQL you could use the CURDATE() function for the 'today' bit, then apply an order and limit to your select statement. For example,
SELECT stall_date
FROM stall_dates
WHERE stall_date >= CURDATE() -- >= assumes you want today's to show too
ORDER BY
stall_date
LIMIT 4
Use ORDER BY stall_date DESC to reverse the ordering if needed.
If your column is a DATETIME field, you can identify the next by using SELECT...WHERE event_date > "2009-11-06" and ORDER BY event_date.
SELECT * FROM so_events
WHERE event_date > "2009-11-06 15:36:00"
ORDER BY event_date ASC
LIMIT 4
MySQL will internally do the work for you and select rows where whose timestamp is greater than the one you specify in the WHERE clause.

Categories