PHP MySQL - Compare Datetime - php

I have a datetime field in my MySql table where the date and time are recorded in the following format:
2010-12-17 18:06:59
I would like to select records where the datetime is in the last 15 minutes. How do I construct my query to do this?
I tried the following but it doesn't work:
// check in last 15 minutes
$time_duration = (15 * 60);
"SELECT COUNT(CounterId) AS Count FROM visitors_counter WHERE TimeStamp > NOW() - $time_duration"
Thanks!

You could just do the entire thing in MySQL:
SELECT COUNT(CounterId) AS Count
FROM visitors_counter
WHERE TimeStamp > (NOW() - INTERVAL 15 MINUTE)

You have to subtract an interval :
SELECT COUNT(*) AS Count
FROM visitors_counter
WHERE TimeStamp > NOW() - INTERVAL 15 MINUTE;
I replaced COUNT(CounterId) with COUNT(*) because the latter is faster if CounterId can't be null. If it can, just replace * with CounterId.
P.S. I don't consider timestamp a good column name because it's a key word. Sure, it works correctly, but it may be "better" to replace it with something else.

Related

Request to find out the date in 2 days

How to write a sql query to find out that there are 2 days left before the current date.
In php, this can be done via:
$res['end_date'] - time () < 86400 * 3;
How can I do the same after 1 sql query, well or better, only 2 days, if less so that it does not work out, well, if it works out, it's okay.
UPD:
It is necessary to compose a sql query that will select only those records that have 2 days left before the end_date expires
The type is int for the field end_date and is stored via the time () function in php.
Can't compose a WHERE clause.
You can use the FROM_UNIXTIME function to convert it to a DateTime you can then use the NOW() plus 2 days to check if the date is under 2 days. You then have to check that the date is before the current time otherwise you'll get dates that have already gone.
SELECT
end_date
FROM
table
WHERE
FROM_UNIXTIME(end_date) <= NOW() + INTERVAL 2 DAY
AND
FROM_UNIXTIME(end_date) > NOW()
Assuming that you are storing an epoch timestamp (the number of seconds since January 1st, 1970), I would recommend:
select *
from mytable
where end_date >= unix_timestamp() and end_date < unix_timestamp() + 2 * 24 * 60 * 60
unix_timestamp() gives you the current epoch. You can use simple math to add two days to that.
The upside of this approach is that this does direct filtering against the store value, so this can take advantagae of an index on end_date - as opposed to converting the timestamp to a date, which requires converting the whole column before the filtering can happen. So this is much more efficient.
You can ajust the inequalities as you prefer. I used a half-open interval (inclusive on the lower bound and exclusive on the upper bound), which is a widely used approach.
I ended up doing this:
$time = time();
$params = $db->query("SELECT * FROM `params` WHERE (`end_date` - {$time}) < 86400 * 3");
And it worked.
I always do
select *
from mytable
where FROM_UNIXTIME(end_date) < NOW() + INTERVAL 2 DAY
This will get results where two days in the future is ahead of the end date ie, anything that will end within 2 days (or has already ended as I didn't add a check for that)
Edit: I see you can't use where
If you cannot use where clause
select FROM_UNIXTIME(end_date) - INTERVAL 2 DAY as end_date
from mytable
And then check in php if the result is before or after. This will show all results however

How can I select data from this week using a Unix timestamp in SQL?

I have two columns in my database named dtp_s and dtp_e. Both of these columns hold strtotime() formatted ints which I then use in my PHP application to calculate hours/minutes between time intervals.
I want to display the 5 most recent records in date order, which works fine when I use this:
SELECT id
FROM _records
ORDER BY dtp_s DESC
LIMIT 5
However, I now want to convert the dtp_s back to a DateTime format in my Query and only pull out the data for that week. The issue I have is the records are for a weekly quota, my idea of pulling 5 records out covers Monday-Fri (which is all that is needed and uploaded) however, the following Monday will show the previous weeks Tuesday, Wednesday, Thursday and Friday as well.
I tried to use date_sub for a one week interval but this seems to only work on DateTime datatype columns, not a Unix timestamp:
SELECT id
FROM _records
WHERE dtp_s > DATE_SUB(NOW(), INTERVAL 1 WEEK);
ORDER BY dtp_s DESC
LIMIT 5
How only select the data that is from the current week by converting my formatted DateTime back to DateTime format? I appreciate any help in advance.
An example of my dtp_s and dtp_e is: 1595570400 1595584800
You can convert the filter value to a unix timestamp with date function unixtimestamp(), like so:
where dtp_s > unix_timestamp(now() - interval 1 week)
Actually, you can directly use unix_timestamp() with no conversion:
where dtp_s > unix_timestamp() - 7 * 24 * 60 * 60
Although unix_timestamp() can be very useful, unix_timestamp(now()) is actually redundant. You can just do the whole calculation in the domain of unix timestamps.

Mysql queries for date difference in days

Need help here, having an mysql table called APPROVAL, there having an id,dateandtime and level, i need a query that selects the id alone with the following condition.
Taking date alone from database and comparing it with current system date, if the days exceeds above 30 and below 60 and also level = 5.
How can I write a query for this.
Thanks in advance.
MySQL has good date arithmetic. For example, the expression
CURDATE() + INTERVAL 30 DAY
gives a datetime value denoting midnight 30 days hence. Similarly
CURDATE() + INTERVAL 61 DAY
yields midnight on the 61st day.
So a query of the form
SELECT ID
FROM APPROVAL
WHERE Level = 5
AND `DateTime` >= CURDATE() + INTERVAL 30 DAY
AND `DateTime` < CURDATE() + INTERVAL 61 DAY
will yield what you want. Notice the use of >= for the beginning of the range of days, and the use of < and an extra day for the end of the range. We do that because we want all items from the 60th day, and none from the 61st day.
A compound index on (Level, DateTime) will make this query very efficient to satisfy.
Notice that an expression like
DATE(`DateTime`) <= CURDATE() + INTERVAL 60 DAY /* slow! */
will also yield correct results, but the presence of the the DATE() function call on the column to be searched makes it unsargeable. That is, it makes MySQL unable to use an index to satisfy the search.
Ok so use this query to retrieve all the IDs that match level 5 and date diff between 30 and 60 compared to the current date.
SELECT id
FROM APPROVAL
WHERE level = 5 && DATEDIFF(NOW(), dateandtime) BETWEEN 30 AND 60
I'd suggest you to order them dy date DESC too.
Hope that helps
I hope, I understood your problem correctly.
select `ID`
from APPROVAL
where `Level` = 5
and ( DATE(`DateTime`) > curdate() + interval 30 day
and DATE(`DateTime`) < curdate() + interval 60 day )
order by `ID` asc;
Where DATE() gets the date from a datetime and CURDATE() is the current system date. With interval you can manipulate a date expression whitout having to worry about its limits.

MySql select if date is NOT more than 15 min ago

I am trying to make a login system that logs you out after 15 minutes of inactivity. Here is my current code for fetching the data:
$itemResult = mysql_query("SELECT * FROM `logins` WHERE token = '$token' AND logged_date xxxxx");
This is where I am stuck. The date is formatted like this: yy/mm/dd h:m
I need to select everything with the correct token that is no more than 15 minutes old. How do I do that?
Explanation:
Because you are using a varchar column type you need to convert them to the same type, either change your database to store the date as a date (typically best practice anyways) or use str_to_date() to convert your string to a date before comparing.
Then we use the NOW() function to get the current datetime, subtract an interval of 15 minutes from the value of NOW() and compare it to the logged_date column
Or you could use Date_format() to convert the now - 15min date to a string
date_format(DATE(NOW() - INTERVAL 15 MINUTE), '%y/%m/%d %h:%i') and then compare your varchar to that
Query:
SELECT *
FROM `logins`
WHERE token = '$token'
AND
str_to_date(logged_date, '%y/%m/%d %h:%i') >= DATE(NOW() - INTERVAL 15 MINUTE)

SQL DATE and TIME to DATETIME

I have date and time column in my table. I want to select all objects which has date and time larger than current time plus one hour:
I have tried the following:
SELECT * FROM mytable WHERE date >= CURDATE() AND time >= TIME(NOW()+INTERVAL 1 hour)
However this is logically not correct. If date is tomorrow and time is less than current HH:MM it will not select that record.
How can I use my date and time to compare with current datetime?
I am using php 5.2 with mysql
First of all, I recommend using a DATETIME column to make this filtering more efficent. However, this works if you cannot change:
SELECT * FROM mytable
WHERE (date = CURDATE() AND time >= TIME(NOW() + INTERVAL 1 hour))
OR date > CURDATE()
You can split your condition into two conditions...
When the date is equal to today and more than an hour ahead of the current time:
date == CURDATE() AND time >= TIME(NOW()+INTERVAL 1 hour)
When the date is greater than today:
date > CURDATE()
...and chain them together using OR and parentheses:
SELECT * FROM mytable WHERE (date == CURDATE() AND time >= TIME(NOW()+INTERVAL 1 hour)) OR date > CURDATE()
First check whether the date is today and if time is greater then current time. The second condition is to check whether the date is greater than current date. Because if the date is greater then current date then automatically it's time is ahead.
SELECT * FROM mytable
WHERE (date = CURDATE() AND time >= TIME(NOW() + INTERVAL 1 hour))
OR date > CURDATE()
SELECT * FROM mytable WHERE date >= CURDATE() AND time >= TIME(HOUR(NOW()) + 1);
or maybe just
SELECT * FROM mytable WHERE date >= CURDATE() AND time >= HOUR(NOW()) + 1;
As indicated by #Pekka, all the answers posted so far will give the wrong answer between 11pm and midnight. I don't work with MySQL, but I can look stuff up. A better approach seems to be the timestamp() function.
This reference states:
With two arguments, it adds the time expression expr2 to the date
or datetime expression expr1 and returns the result as a datetime value.
Why not use timestamp() with two arguments?
You can do this.
SELECT
*
FROM
mytable
WHERE
CONCAT( date, " ", time ) > (NOW() + INTERVAL 1 HOUR );
Personally I suggest that you get rid of the separate fields for date and time and create a consolidated 'DATETIME' field. I also suggest adding an INDEX to that field.
That would make your queries better and faster. :)

Categories