How to delete rows based on date differences with MySQL? - php

I need to delete rows where a datetime field is over 2 weeks old.
This is what I have came up with
$duration = Date::WEEK * 2; // int(1209600)
$query = 'DELETE FROM properties
WHERE TIMEDIFF(' . date(DATE_ISO8601) . ', reserved_datetime) > ' . $duration;
I don't often write complicated queries (preferring to do stuff in PHP, where I'm more comfortable) but I'd like to know more about them, plus doing this sort of thing in PHP would be very inefficient and I am handling a large amount of rows.
Anyone know what I'm doing wrong? Cheers.
Update
I gave Wallyk's answer a shot, changing it slightly in phpMyAdmin to SELECT just so I could see what was going on.
This is what I used
SELECT *
FROM properties
WHERE date_sub( `reserved_datetime` , INTERVAL 2 week ) >0
LIMIT 0 , 30
The only problem however, is that it has returned rows where the reserved_datetime is 2010-02-28 10:45:59, definitely less than 2 weeks ago (from now).
I thought of checking MySQL's internal date. I have been using date(DATE_ISO8601) in my queries, because MySQL's NOW() wasn't exactly right (it just returned if interested 2010-02-28 20:09:19).
Is there a way to specify the current date in that query? Any other suggestions?
Many thanks
Another Update
Here is a screenshot from phpMyAdmin that may demonstrate anything better than my words can. Oh, and the reason it has returned 3 only is because all the others have blank values, i.e. 0000-00-00 00:00:00

wallyk's answer is not correct. Think about what you're doing - subtracting two weeks from almost any date will still be greater than zero (zero = 1/1/1970). I think you want something more like this:
DELETE FROM properties WHERE DATE_SUB(NOW(), INTERVAL 2 WEEK) > reserved_datetime

Use:
FROM PROPERTIES p
WHERE p.reserved_datetime <= DATE_SUB(NOW(), INTERVAL 2 WEEK)
Mind that because of using NOW(), the two week old date will include the time portion.

I don't have a mysql database so I can't say if it works for sure, but it does in postgresql:
DELETE FROM properties WHERE (NOW() - reserved_datetime < interval '2 weeks')

Try this instead:
$query = 'DELETE FROM properties
WHERE date_sub(reserved_datetime, interval 2 week) > 0';
This assumes that reserved_datetime is the field name in the table.
(Tested with MySQL 5.0.46-standard.)

Related

Manipulate a string as a date with MySQL?

I am working with a MySQL table which has entries like the following for the timestamp 2016-12-28T21:42:53.000-04:00 provided as a CHAR field.
One of the tasks I need to do is to retrieve all the records for the current date.
Right now what I am doing is getting the current date into a php variable ($date) in the same format as the one in the MySQL table. ie 2016-12-28 and use a LIKE statement to find all the records matching it.
The problem comes when I need to find all the records for the last 10 days for example.
Is there anyway to convert that field into a valid date one which I can use for more complex queries like find the last 10 days, etc?
Any tip in the right direction will be appreciated,
Thanks
You can just convert it to a date. One method is:
select date(left(field, 10))
I should add that this will work just as well in a where clause:
where date(left(field, 10)) >= date_sub(curdate(), interval 10 day)
But . . . using functions on columns precludes the use of indexes. In this case, you have a good date format, so you could do:
where field >= date_format(date_sub(curdate(), interval 10 day), '%Y-%m-%d')
This version can take advantage of an index on field.
All that said . . . storing fields using the proper type is highly recommended.

How to filter MySQL dates?

I'm trying to do a SELECT * FROM but only items that are less than 30 days old. Here is my select code:
SELECT * FROM `{$table_name33}` WHERE `type`='wpst-requiredinfo' ORDER BY `foreignkey` ASC;
However, my problem is that I can't figure out how to add WHERE AND last_updated is less than 30 days.
I'm not exactly sure how to write the query, but the date is showing up like this: 1428412603 in the table column, it doesn't look much like a date to me. I don't know where to start.
Try this where clause:
WHERE `type`='wpst-requiredinfo' and
last_updated >= date_sub(now(), interval 30 day)
EDIT:
Your date seems to be in Unix time format.
WHERE `type`='wpst-requiredinfo' and
last_updated >= unixtime_timestamp() - 30*24*60*60
Note: this puts all the functions on the current time. In particular, it does not use FROM_UNIXTIME(last_updated). This ensures that an index can be used for this part of the query. The best index would be on (type, last_updated).

Postgresql search for items older than a threshold

Seems like this should be a simple thing to do, but the date/time operations in postgresql are killing me. All I'm looking to do is search for items older than 10 minutes. Coding language is PHP.
Field event_time is: timestamp without time zone NOT NULL
$sql = "SELECT * FROM incidents WHERE
event_time < ( now() - interval '-{$threshold} minutes' )
AND submitted=0 ";
This query is returning all results instead of items older than 10 minutes. Do I need to type cast that event_time field somehow?
By using a negative threshold value, you have a double negative, so you are searching for everything less than ten minutes in the future (which would naturally return everything). Just use interval '{$threshold} minutes}'

Getting an event from a database a week in advancee

I am currently developing a sports website where one of the pages with be forthcoming fixtures in which the user will be able to what team and where the team are playing their next match.
I have a database with the following fields...
ID
TEAM NUMBER
OPPOSITION
VENUE
DATE
MEET TIME
MATCH TYPE
So a row of data pulled from the DB and print_r'd may look like this
ID=>[1] TEAM NUMBER=>[1] OPPOSITION=>[YORKSHIRE] VENUE=>[HOME] DATE=>[2009/4/25] MEET TIME=>[13.00] MATCH TYPE=>[CUP]
My problem is i cannot work out how to show the next match dependent on what the current date is, so for example for now I want the site to show all the games that will happen over the weeken of the 25th April 2009 and then once that has gone the fixtures for the next weekend.
Hope this makes sense and some one give me an idea of how to tackle this.
select * from my_events where date between now() and date_add(now(), interval 7 day);
Should do it I think.
Instead of relying entirely on MySQL, you can also use PHP's strtotime() function:
$query = "select * from my_events where date between now() and ".
date("Y-m-d", strtotime("+1 week"));
For MySQL check out the Date and Time functions. You can use a combination of CURDATE() and ADDDATE() to achieve what you need.
Your description is very vage but try something like this:
SELECT all_fields_you_need
FROM table_name
WHERE `DATE` > CURDATE() AND `DATE` <= DATE_ADD(CURDATE(), INTERVAL 7 DAY)
ORDER BY `DATE` ASC
(not tested, just written as it came into my mind...)
Load it all into an array and display the data
you can get the system date (in Oracle using sysdate) and then add to it, so look for all records where DATE = sysdate + 7. You may have to play with this a little, formatting the date so that sysdate + 7 returns a date without the time, but that is basically what you need.
EDIT:
If you want the event between now and a week from now (if games are only on the weekend, then this will return next weekend's games) do
DATE > sysdate AND DATE <= sysdate + 7
To get the next match for team xxx
SELECT *
FROM myTable
WHERE TEAM NUMBER = xxx
AND DATE = ( SELECT MIN(DATE)
FROM myTable
WHERE TEAM NUMBER = xxx
AND DATE > NOW() )
I suspect this is what you really want, if matches only take place at weekends (which seems to be an assumption from your question).
Today + 7 days is not the same as next weekend unless today happens to be the same day of the week as the match.

MySQL date/time calculation

I have a date and time column in my mysql table called start_date and start_time respectively. I want my users the ability to set reminders for themselves to be sent X hours before start_time, min. 1 hour and max 24 hours.
I'll be running a CRON script to send these reminders. Right now I do:
SELECT * FROM auctions WHERE start_date=CURDATE() AND status='0'
To get all the auctions that will be starting today and haven't yet started. My question is, how can I figure out if the time now is X hours before start_time so I can send them a reminder if it is.
Any suggestions at all?
Something like this:
SELECT col1, col2, col3
FROM records
WHERE (records.startDate BETWEEN NOW() AND ADDDATE(NOW(), INTERVAL 9 HOUR))
AND (records.status = '0');
Is there some reason why you can't just use a simple timestamp field instead of one for date and one for time. That way you could find all the ones that start in the next 5 hours (say), by doing
select * from auctions where start_ts between now() and now() + interval '5 hours';
Note: the interval syntax varies slightly between databases, and that's the one for postgresql, so you might have to change it slightly for mysql.
I actually did it this way before all the answers were sent and its working. Because i'm on a deadline I can't go back and change it :)
$sql="SELECT HOUR(ADDTIME(CURTIME(),'$hour')) as remindHour, HOUR(CURTIME()) as curHour";
$result=$this->db->query($sql);
extract($result->getAllSingle());
if ($remindHour <=$curHour) {
// Send reminders
}
Can you use unixtime to save the time?
Since PHP has a wonderful function called strtotime.
Within in you can say. strtotime("+20 hours") and get the unixtime for 20 hours from now.
Then its just a matter of which field is larger than the other, if so, send the notification.

Categories