user1106464
user1106464

Reputation: 111

Timestamp comparison to delete when mysql timestamp > 20 minutes

I want to do something which is not complicated but I do not manage to succeed even after I tried a lot of things....

First of all, I have a database mysql with a row of timestamp type. I insert into it elements with a date like this:

$date = date('Y-m-d H:i:s', time());
$req =mysql_query("INSERT INTO my_table (id, departement, voie, date,message)
    VALUES ('', '$departement_token', '$voie_token','$date' , '$message_token')");

The result of this code line is a date element like this : 2012-07-19 20:18:17

I want to delete all elements with a date > current date + 20 minutes and I do not succeed...

I tried this:

mysql_query("DELETE FROM my_table WHERE  DATE_SUB(date,INTERVAL 20 MINUTE) ORDER BY date");

And this:

$req=mysql_query("DELETE FROM my_table WHERE date >= TIMESTAMPADD(MINUTE,-20,NOW())
                  ORDER BY date");

And this:

$timePlus20min = time() + 1200;
//et on compare les deux dates
$req = mysql_query(
    "DELETE FROM my_table WHERE UNIX_TIMESTAMP(date) >= '$timePlus20min' ORDER BY date");

But none of this works. Could you help me please, I think it's not too difficult but I'm out of ideas...

Upvotes: 3

Views: 942

Answers (4)

Limitless isa
Limitless isa

Reputation: 3802

$period=date('Y-m-d H:i:s',time()-(60*60*6)); // 6 hour before

"SELECT * FROM limitlessisa WHERE UNIX_TIMESTAMP(REG) > UNIX_TIMESTAMP('$period')";

REG // timestamp row name

This is working. 6 hours before listing data

Upvotes: 3

Wolfram
Wolfram

Reputation: 8052

In all your queries you forgot the WHERE keyword so they are syntactically wrong. Also, the ORDER BY statement has no effect as you are not executing a SELECT query. There is no result that could be ordered. Instead, a single table DELETE query returns a count of the number of deleted rows.

DELETE FROM my_table WHERE date >= DATE_ADD(NOW(), INTERVAL 20 MINUTE);

As I do not know your table structure, I tried this query with the following table:

CREATE TABLE `datetest` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=3 ;

Upvotes: 2

Sergey Eremin
Sergey Eremin

Reputation: 11076

Try this:

DELETE FROM my_table WHERE UNIX_TIMESTAMP(date) > 60 * 60 * 20 + UNIX_TIMESTAMP();

Upvotes: 0

PoulsQ
PoulsQ

Reputation: 2016

try this :

$req=mysql_query("DELETE FROM my_table WHERE date <= ".date("Y-m-d H:i:s", mktime(date("H"), date("i")-20, date("s"), date("m"), date("d"), date("Y")));

Bonne chance à toi / Good luck

Upvotes: 1

Related Questions