user1834464
user1834464

Reputation:

SQL query not doing anything

I am trying to delete a row from my wp_pagesvisites table.

global $wpdb;
$time = time();


$timebd = $wpdb->get_col("SELECT Timestamp FROM wp_pagesvisites");


foreach ($timebd as $v)
{
    //echo ($time - $v)."  -  ";

    if ($v - $time > 600)
    {   

        $wpdb->query(   
                $wpdb->exec(
                    "DELETE FROM wp_pagesvisites WHERE Timestamp=$v"
                )
        );
    }
}

It does enter my if condition because if I do an echo on $time - $v, some are greater than 600, so I think it's my SQL query that is no good. Hopefully you can see my error.

Upvotes: 1

Views: 230

Answers (3)

Zz Oussama
Zz Oussama

Reputation: 229

You can do this :

$bdd your database

$wpdb = $bdd->prepare("DELETE FROM wp_pagesvisites WHERE Timestamp <'$v' "); $wpdb->execute();

or

$req = $bdd->exec("DELETE FROM wp_pagesvisites WHERE Timestamp < '$v' ");

Upvotes: 0

Clockwork-Muse
Clockwork-Muse

Reputation: 13056

Warning - you appear to be open to SQL Injection, you should be using parameterized queries. Also, you're going about this in the most inefficient way possible (by looping over every row). What you should be doing is telling SQL to delete rows over a certain age; something along these lines (may need tweaks to work in your environment/language):

$time = time() - 600;

$wpdb->query(   
     $wpdb->exec(
          "DELETE FROM wp_pagesvisites WHERE Timestamp < $time"
     )
);

... And that should remove all the rows for you.


Besides the problem that @mavili mentions, you're also thinking about date/time/timestamps wrong. You're comparing all values to themselves, when you want everything within a certain range. It's almost best to think of timestamps like doubles - they can't be exactly compared to each other, only as parts of ranges (>=, <, etc).

Upvotes: 1

mavili
mavili

Reputation: 3424

you say " $time - $v, some are greater than 600" but your if condition is vice versa (i.e. $v - $time)

Upvotes: 3

Related Questions