Subtract 5 minutes from a date value - mysql

I'm currently writing a snippet of code which will look through the database and see if any admins are currently online and show them on the side of the page as being online.
Every time a user browses through a page on my site (when they are logged in) it grabs the current time and updates a column called lastseen.
I have a role column that marks a user from an admin and what I want it to do is query the database for all the admins and check the lastseen column and if that time is within 5 minutes of the current time then output them to a row which I can then take and format later.
This is what I currently tried but nothing came back.
SELECT username, role, lastseen
FROM database.accounts
WHERE lastseen >= DATE_SUB(NOW(), INTERVAL 10 MINUTE) AND role='admin'
I am storing lastseen as date('Y-m-d H-i-s') from PHP so it looks like this
2017-02-18 16:07:42 in the database.

What is your datatype for lastseen, Your query seems correct , just try with
SELECT username, role, lastseen FROM database.accounts
WHERE STR_TO_DATE(lastseen, '%Y-%m-%d %H:%i:%s') >= DATE_SUB(NOW(), INTERVAL 10 MINUTE) AND role='admin'
Also make sure your PHP and MYSQL Server have same timezones

Related

How I do select from mysql latest value, if the value is not older than 3 months

I am trying to find clients, who have lot logged into my website in 3 months, to send a reminder.
My issue is if I do a interval query, there are always a result for a client, because the query select the date older than 3 months, even if the client has logged in at a later stage.
So I only want to see a result if a client logged in more than three moths ago. Currently I get results for three months a go, even if a client logged in more recent. If he logged in recently, the client should not show up in result
SELECT Client, IP, Date from iplog
WHERE Date = (select max(Date)from iplog group by Client) AND Date < DATE_SUB(now(), INTERVAL 3 MONTH)
I would handle this via an EXISTS clause:
SELECT Client, IP, Date
FROM iplog ip1
WHERE NOT EXISTS (SELECT 1 FROM iplog ip2
WHERE ip1.Client = ip2.Client AND
ip2.Date >= DATE_SUB(NOW(), INTERVAL 3 MONTH));
The logic here is that we check, for each client record, that the client does not have any other record reflecting a recent login within the last 3 months. If so, then all of that client's records would be returned.

Fetch mysql data of timstamp depending on time given

I have a column with timestamp, contain example value "2014-04-16 18:00:00","2014-04-17 18:00:00"....
Now, if I will call a page before "2014-04-17 12:00:00" I need this value-"2014-04-16 18:00:00"
And if I call my page after "2014-04-17 12:00:00" I need this value "2014-04-17 18:00:00".
I think my question is very complicated to understand, having complications in date & times, please check date & time properly.
I want to fetch this data from DB in mysql, The page I was saying is that where I'm going to add your mysql query.
Thanx in advance
Generalising what your asking for a bit the following will return dates from the previous day if it's before noon and dates from today if it's after noon:
SELECT date_column
FROM yourTable
WHERE DATE(DATE_SUB(NOW(), INTERVAL 12 HOUR)) = DATE(date_column);
Edit:
The WHERE clause First gets the current time (NOW()) and subtracts 12 hours. This wont affect the date unless the time is before 12. This means DATE_SUB(NOW(), INTERVAL 12 HOUR) gives us today if it's after noon and yesterday if it's before.
We then check if the date_column matches the date we've created (using the DATE function so that the time is ignored).
Adding some rows to the SELECT may help you see how these dates are built up.

Working with a non-standard date time format in MySQL

I have a system that auto-populates a mysql database with data. Unfortunately the the only time value is being stored in the format YYYYMMDDHHMMSS.SSS. Have a script that runs against the data in the database in a 30 minute cron to alert on certain data trends. The problem that I'm having is that the data in the database goes back 7 days. I only want the script to run against the past 30 minutes of data.
I tried using something like:
SELECT foo FROM table WHERE StartTime >= DATE_SUB(NOW(), INTERVAL 30 MINUTES);
Unfortunately this didn't work, I'm assuming because the stored time formation does not match a standard SQL Timestamp format.
Can anyone suggest an alternate method? Thanks.
StartTime >= DATE_FORMAT(DATE_SUB(NOW(), INTERVAL 30 MINUTE),'%Y%m%d%H%i%s.000')

Logic for dates in sql query for mysql

Hi i am totally confused with a date logic in my mysql query for a cron job to be run everyday at 12:00 AM
I am working on a auto listing website where the car listings are having a expiry date in mysql datetime format.
All the expired listings will be deleted from the website after 7 days from the datetime of the expiry
When the cron job will run it has do following things
Task 1 - Send an email alert to the users telling them that their listing has expired.
So I need to select all those listings which have expired since last time the cron job has been run and not include listings before that in order to send the expiry alert email only once per listing.
I tried following sql query for this task (Again confused with this as well)
SELECT car_id FROM cars WHERE expiry_date > DATE_SUB(NOW(), INTERVAL 1 DAY) AND expiry_date < NOW()
Task 2 - Will send an email alert to users telling them that listing is going to be permanently deleted after 24 hours.
So I need to select all those listings which are going to be deleted in more than 24 hours / 6 days have passed since they were expired and i need to make sure that they get minimum 24 hours time to renew them. Also i need to select / build the sql query in such a way that only those listings get selected which are going to expiry in 1 days and not other in order to avoid multiple email alerts instead of one time email alert
I tried following sql query for this task (I am totally confused with this query)
SELECT car_id FROM cars WHERE expiry_date > DATE_SUB(NOW(), INTERVAL 7 DAY) AND expiry_date < DATE_SUB(NOW(), INTERVAL 1 DAY)
Task 3 - Delete all the listings which were expired more than 7 days ago
I tried following sql query for this task
SELECT car_id FROM cars WHERE expiry_date < DATE_SUB(NOW(), INTERVAL 7 DAY)
Please help me in perfecting all the 3 queries so that the cron does it job exactly as i want. Also please let me where it has to >= (greater than or equal to) or <= (less than or equal to)
Here is the sqlfiddle table structure and couple of records (though they are not expired yet)
http://sqlfiddle.com/#!2/cfcdf
I will really appreciate the help.
Is this what you are looking for? Please try to add another column to see the differnce between expiry_date and current date time for you to get a better idea of the dates you are dealing with. Please look into some dates functions in MYSQL.
SQLFIDDLE DEMO
-- 3rd query expiry dates older than 7 days from
-- today
SELECT car_id, expiry_Date,
DATE_sub(NOW(), INTERVAL 7 DAY)
FROM cars
WHERE expiry_date <=
DATE_sub(NOW(), INTERVAL 7 DAY)
;
-- same
SELECT car_id, expiry_Date,
DATE_ADD(NOW(), INTERVAL -7 DAY)
FROM cars
WHERE expiry_date <=
DATE_ADD(NOW(), INTERVAL -7 DAY)
;
-- 2nd query going to expire in exactly 1 day
SELECT car_id, expiry_date,
Now() + interval 1 day
FROM cars
WHERE expiry_Date = Now() + interval 1 day
;
-- 1st query: expired
SELECT car_id FROM cars
WHERE expiry_date < Now()
;
-- 1st query: expired last 24 hours
SELECT car_id,DATEDIFF(expiry_date, Now())
FROM cars
WHERE expiry_Date < Now()
AND expiry_Date >= Now() - interval 1 day
;
Check out these queries
select * from cars where datediff(EXPIRY_DATE,now())=-1;
select * from cars where
datediff(DATE_ADD(EXPIRY_DATE, interval 24 hour),now())>=1 and
datediff(DATE_ADD(EXPIRY_DATE, interval 24 hour),now()) <=2;
select * from cars where datediff(expiry_date,now())<=-7;
ope they are working according to your need.
fiddle http://sqlfiddle.com/#!2/785ea/5
There is nothing significantly wrong with your queries, if you do not understand the functions that you have used then google them and read about them until you do.
There is a fundamental problem in your approach in that it relies on the cron job being run at exactly 24 hour intevals - to the milisecond - or there will be double ups and/or omissions.
You need another table to store details of when your batch program last ran; intitialise this with 1 row with a date a long time in the past so that we have a starting point.
You can get the most recent batch by SELECT MAX(date_ran) FROM BatchRecordTables. Store this in a local variable T0. Get the current time, store this in a local variable T1 (Do not use NOW() in multiple queries as they will be slightly differant times and you need them to be the same). I do not know the syntax for this is MySQL - you will have to look it up.
Your situations then become.
Send email to people whose listings have expired since that last time the cron job was run i.e. SELECT car_id FROM cars WHERE Expiry_Date BETWEEN T0 AND T1. This will only select people whoose listings have expired between this batch and the previous one.
For the second case, we need to know that these people have got the first email i.e. that their listing had expired before the last batch run so SELECT car_id FROM cars WHERE Expiry_Date BETWEEN DATE_SUB(T1, INTERVAL 6 DAY) AND T0. This will only select people whoose listings expired before the last batch (i.e. they got the exprired email) and more than 6 days ago.
Same logi applies - we want to know they got the second email. SELECT car_id FROM cars WHERE Expiry_Date BETWEEN DATE_SUB(T1, INTERVAL 7 DAY) AND DATE_SUB(T0, INTERVAL 6 DAY)
May I also suggest that you do not permenantly delete the listings but either copy them to a DeletedListings table or Flag them with a Deleted column - each has its own pros and cons. In the information age, never throw data away - you never know when it might be valuable.

PHP / MYSQL Date Calculations for automated billing

I am sending 'reminder' messages every 30 days, and was wondering how to calculate the time based on the timestamp I placed on the originating users signup date.
I will have a cron job run every day to query and send the messages, but I am unsure how to query the date so it will select the appropriate accounts each day and send the messages.
Any sure fire ways to do this?
Use the DATEDIFF function to return the difference between then and NOW() in days.
Something like the query below should fit. If you can give me any more details on what / how you wish to query I can make this SQL more specific. This current query selects users whose signup_date was 30 or more days ago:
SELECT * FROM users WHERE DATE_ADD(signup_date, INTERVAL 30 DAY) <= NOW()
For further information:
MySQL Date and Time Functions
Some notes on INTERVAL usage