user2230442
user2230442

Reputation: 13

Check Query for DateTime being X seconds ago

I am using PHP and MySQL to create a flood-filter for my forums I've recently created and I did research this, but little results came and only one of them potentially brought me further to my resolution.

This is the code

$overview_threads = mysql_query("SELECT * FROM `forum_posts` WHERE `author`='".$_SESSION['username']."' AND TIMESTAMPDIFF(SECOND, `created`, now()) <= 20");

The code is made in attempt to select a thread made by the user within an interval of 20 seconds or less and then do an if statement to prevent the user of posting within that time.

What do I do for this?

Upvotes: 0

Views: 52

Answers (1)

Mike Brant
Mike Brant

Reputation: 71422

First, you should probably use DATE_SUB() for this as it will be much more index friendly (you need an index on created of course)

SELECT * FROM `forum_posts`
WHERE `author` = ?
AND `created` >= DATE_SUB(NOW(), INTERVAL 20 SECONDS)

Second, in order to determine if you have a record, you will have to look at the result set.

$result = mysql_query($query); // query is that shown above
if (false === $result) {
    echo mysql_error();
} else if (mysql_num_rows($result) > 0) {
   // you found a match
}

Third, you should really look at using mysqli or PDO instead of mysql_* functions, as these are deprecated.

Upvotes: 1

Related Questions