Relm
Relm

Reputation: 8282

How to select IP and check if the time it was inserted is not less than 2min

  1. I want to check if the time a message was inserted into a table is not less than 2min from the same IP address.

  2. if time is not yet 2min from last insertion, echo how many minutes and seconds left before a user can come back and send a message from that very same IP.

  3. I have a column 'mtime' (mysql, Type: datetime) which records the time a message was inserted into the table, so i hear my format must be in Unix, how do i convert to that in this process?

Here's my rough PHP.

   require_once '../php/db_conx.php';
if (!$con){
die(mysql_error());
}
  $ip = mysql_real_escape_string($_SERVER['REMOTE_ADDR']);
    $query = "SELECT * FROM messages WHERE ip = '$ip' AND mtime >= ' ".strtotime('2 minutes')."'";
    $result = mysql_query($query);

    if (mysql_num_rows($result) > 0) {
      echo "You can only send 1 message every 2min.(eg $timeleft) before you can send your next message.."; 
    } 

Upvotes: 0

Views: 106

Answers (1)

Tin Tran
Tin Tran

Reputation: 6202

SELECT * FROM messages WHERE ip = '$ip' AND mtime >= NOW() - INTERVAL 2 MINUTE

to get seconds left

SELECT mtime - (now()- interval 2 minute) AS secondsLeft 
FROM messages 
WHERE ip = '$ip' AND mtime >= now() - interval 2 minute;

your php may look like something like this

$result = mysql_query($query,$con);
if ($row = mysql_fetch_array($result,MYSQL_NUM))
{
    echo "seconds Left: ".$row[0];
}
else
{
    //some code here to insert new record maybe
}

Upvotes: 2

Related Questions