A not working mysql delete query. Why? - php

I have a table with 3 rows and one of those contains a unique time code (ex: 1308162911). There are a lot of these records but I want to delete all records which are bigger than one day (AKA 86400 seconds). I have this query but it doesn't work (nothing happens):
$db = mysql_connect($hostname, $db_user, $db_password);
mysql_select_db($database,$db)or die( "Unable to select database");
$now = time() - 86400;
$delete = ("DELETE FROM $tbl WHERE time > '$now'");

I'm not sure about MySQL, but probably you need something like that:
DELETE FROM $tbl WHERE DATEDIFF('$now', time) > INTERVAL 1 DAY

How about something like this:
$yesterday = strtotime('-1 day');
$delete = "DELETE FROM $tbl WHERE time > FROM_UNIXTIME($yesterday)";
The above query will delete all rows where the "time" value is greater than exactly 24 hours ago. This assumes that the "time" field is a TIMESTAMP, DATETIME or DATE type. If you want to delete records that are older than a day, change the > for a <.

select * from table
where now() - interval 1 day > from_unixtime(unix_timestamp_field)
if this is what you're lookin for convert the select into a delete query

This should work:
DELETE FROM $tbl
WHERE FROM_UNIXTIME(`time`) > DATE_SUB(NOW(), INTERVAL 1 DAY);
Or otherwise, in your code, I think you should remove the single-quotes around $now. However, I think it is a good idea to do it all as part of a MySQL query to avoid any time differences between PHP and MySQL if they are both running in different time-zones

Unix timestamp increases as time goes on so your query will delete all records more recent than 24 hours ago, not longer than 24 hours ago.
You should be OK to remove the single quotes around the timestamp value too.
If you're still having a problem please can you include the line of code that executes mysql_query() and the format of the database (output of SHOW CREATE TABLE myTable)

Related

storing time to a db and comparing with current time

i have a simple question, that just needs verification, it's about how time is stored in mysql, here is how i store it:
if(isset($_SESSION['user']))
{
$u_id=$_SESSION['user'];
//insert current time to db, i set the type of time to TIME
$query="INSERT INTO time(id,u_id,time) VALUES('NULL','".$u_id."',CURTIME())";
mysql_query($query);
}
that is how i store it, now i would also need to compare it to a value, later on:
//set current time
$curr_time=time();
//set maximum time to 5min
$max=300;
//get previous time from db
$query="SELECT * FROM time";
$result=mysql_query($query);
$row=mysql_fetch_array($result);
$prev_time=$row['time'];
//get difference in time
$diff=$curr_time-$prev_time;
//if max time is surpassed
if($diff>$max)
{
echo "maximum time surpassed!";
}
that's the simple code, first of all, is the syntax for inserting the time to the table okay(the CURTIME() thing), also is the comparison fine, will the result stored in $diff yield seconds?thank you, and sorry if you think this question is a waste of time.
CURTIME() will only give you the time, you likely want NOW() which is the date and time. Then you will need to use strtotime to convert the saved value from the database to seconds since epoch.
Do it in your query:
$query = "SELECT id FROM time WHERE time + INTERVAL 5 MINUTES > NOW()";
is there are no results, time has passed.
MySQL has terrific time and date handling functions. Use them.
(I'd also add some extra parts in the WHERE clause, if you have more than one record, you'll be looking at the wrong one probably.)
Since CURTIME is only on a daily basis and I suspect you want your function to cover the span over days I'd suggest you use NOW() instead as it gives you this format instead:
2012-11-06 09:39:34
also is the comparison fine, will the result stored in $diff yield seconds?
You can't directly compare mysql CURTIME() with time() function in PHP.
For example:
In MySql:
CURTIME() will return only time.
select CURTIME();
+-----------+
| CURTIME() |
+-----------+
| 14:15:11 |
+-----------+
In PHP
time() will return current Unix timestamp.
echo time();
1352191547
Look at sberry's answer for compassion.

mySQL Select records within past hour

I'm setting up basic cookie tracking and validating that by making sure the cookie is on their computer AND their IP matches the record I stored AND the record was stored within the past hour. I'm getting hung up on selecting the mySQL data from within the past hour.
As it stands, the column in my table is called 'timestamp', and it just contains the full timestamp inserted with NOW(). I checked around and thought I found the right call, but this didn't work:
$q = "SELECT * FROM conversion_data WHERE ip='$ip' AND timestamp < DATEADD(HOUR, -1, CURRENT_TIMESTAMP) ";
Taking out the timestamp call, it all works fine, so it's just that one part.
Thanks!
Try:
$q = "SELECT * FROM conversion_data WHERE ip='$ip' AND timestamp > DATE_SUB(CURDATE(), INTERVAL 1 HOUR)";
Your current query will select rows that are older than one hour. Changing the timestamp predicate so that it will fetch rows that have a time that is newer than or equal to, i.e. greater than or equal to, should work.
$q = "SELECT * FROM conversion_data WHERE ip='$ip' AND timestamp >= DATEADD(HOUR, -1, CURRENT_TIMESTAMP) ";
Please note that I'm not sure if dateadd works like this for mysql, apply a relevant function in your case.

Query to select records from a database that were created from a certain time in the past until now

I'm relatively a newbie, would appreciate help :)
I am looking to find entry(ies) from a mysql table which were created some time between now and a certain timestamp in the past. This time in the past is stored in a variable (say $timeinthepast, a few hours ago or yesterday, whatever). And the column 'timecreated' in the table is the timestamp of the creation of entry.
Would the following work? If not, what would?
Thanks!
<?php
$query = mysql_query("SELECT * FROM table1
WHERE timecreated = DATE_ADD(NOW(), INTERVAL -$timeinthepast)");
?>
I am basing this on: Query to select records from a database that were created within the last 24 hours
As long as $timeinthepast is valid (1 MONTH, 2 HOUR, e.g.) in the sql you can try BETWEEN
$query = mysql_query("SELECT * FROM table1
WHERE timecreated BETWEEN
DATE_SUB(NOW(), INTERVAL $timeinthepast) AND NOW()");
I find that the between syntax is the most freindly to use. I have not tested this sorry :)
Select * from `table1` where `timecreated` between DATE_SUB(NOW(), INTERVAL 1 month) and NOW()
You will need to make your time in the past a whole unit of some description.

How to delete rows based on date differences with MySQL?

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.)

MySQL: How many minutes ago was DB updated?

I need to keep a field in a data-base and update it with a time somehow, then later I need to check that time to see if it was over 30 minutes ago or not, and if not, how minutes left until 30?
I am going to be doing this with PHP+MySql can anyone tell me the simplest way to do this?
Thanks!!
Let's assume you want to know how long ago the last update/insert in the table occurred.
You can set up a table with a timestamp field with an on update clause
CREATE TABLE foo (
id int auto_increment,
ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
primary key(id),
key(ts)
)
and then query the record with the largest value in ts
SELECT
TIMEDIFF(Now()-Interval 30 Minute, ts)
FROM
foo
ORDER BY
ts DESC
LIMIT
1
edit: This also works if you want to get all records that have been inserted/modified within e.g. the last 12 hours.
SELECT
TIMEDIFF(Now()-Interval 30 Minute, ts)
FROM
foo
WHERE
ts > Now()-Interval 12 hour
ORDER BY
ts DESC
edit2: there's also an off chance you might be interested in http://dev.mysql.com/doc/refman/5.1/en/show-table-status.html:SHOW TABLE STATUS returns the following fields:
...
Update_time
When the data file was last updated. For some storage engines, this value is NULL. For example, InnoDB stores multiple tables in its tablespace and the data file timestamp does not apply. For MyISAM, the data file timestamp is used; however, on Windows the timestamp is not updated by updates so the value is inaccurate.
I could wrap all you insert and update MySql calls in a function something like the following:
function MySqlQuery($query, $res){
$result = mysql_query($qs, $res);
if($result === false){
mysql_query("QUERY STRING TO UPDATE FIELD IN DATABASE WITH NEW TIME", $res);
}
return $result;
}
Replace the "QUERY STRING TO UPDATE FIELD IN DATABASE WITH NEW TIME" with an actual update query and you should be good to go.
What I do is, put a Time Stamp on the latest record. Pull the latest record with a MySQL Query and then use the mysql fetch array function to get the time of that last record. This goes the same for using a database that is updated with the time only.
You would be able to manipulate that time with a function that compares the current time to the time on the record. From there you can display the time since last posting, and if it is over 30 minutes you can make it echo a message.
$currenttime = /* PHP Time Formatting you wish to use. */
$query = mysql_query("SELECT time FROM database");
$row = mysql_fetch_array($query);
echo "Last Record Posted #" . $row['time'];
$timesince = $currenttime - $row['time'];
echo "Time Since Last Post:" . $time - $row['time'];
if($timesince >= "30"){
echo "Over 30 Minutes!";
}
Let me know if you have any questions. The above code should give you an idea of how it would work, but it is a rough example.
Best of Luck!!
EDIT:::
Sorry, I misread the question, You would still need to enter the time into the database. You can still use the above code to pull the time and see if it is greater than 30 minutes or not.
For the Time Stamp check out the PHP Time Manual. You will want to pick the same time format for both the MySQL Input and the code I posted above.

Categories