如何选择IP并检查插入时间是否不小于2分钟

时间:2013-11-30 05:06:37

标签: php mysql sql datetime time

  1. 我想检查一条消息插入表中的时间是否距同一IP地址不少于2分钟。

  2. 如果时间还不到最后一次插入的2分钟,则回显用户返回并从同一IP发送消息之前剩余的分钟数和秒数。

  3. 我有一个列'mtime'(mysql,Type:datetime),用于记录消息插入表中的时间,所以我听说我的格式必须在Unix中,我该如何转换为过程

  4. 这是我粗略的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.."; 
        } 
    

1 个答案:

答案 0 :(得分:3)

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

剩下几秒钟

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

你的php可能看起来像这样

$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
}