困惑的php / Mysql时间算术行为

时间:2011-12-15 08:13:54

标签: php mysql

我正在尝试选择在过去90秒内输入的所有条目以及因此获取的每一行:

  • 显示插入时间与当前时间之差(差异)
  • 显示记录将超过90秒(待定)的剩余秒数

表格结构:

attempt_id    |   username   |   attempt_ip   |   attempt_time  

这是我正在使用的查询:

SELECT *, (NOW() - attempt_time) diff, ( 90 + attempt_time - NOW() ) pending, 
NOW() nw FROM failed_login WHERE (username = 'some_username' 
OR attempt_ip = '127.0.0.1') AND NOW() - attempt_time < 90;

但是我得到了不一致的结果:

测试运行 A Test Run

另一次试运行
enter image description here

完整代码(如果您想尝试)

<?php

date_default_timezone_set('UTC');

function please_monsieur_db($qry) 
{
    $con = mysql_connect("localhost", "root", "");
    if(!$con)
        die("Unable to connect. " . mysql_error());

    $db = mysql_select_db("temp_test");
    if(!$db)
        die("Unable to select database. " . mysql_error());

    $res = mysql_query($qry);
    if(!$res)
        echo "\nQuery failed: $qry" . mysql_error();

    return $res;
}

/* Insert 3 records with a time gap between 2 and 8 sec after each insert */
$k      = 0;
while($k != 3)
{
    $q      = "INSERT INTO failed_login (username, attempt_ip) VALUES ('some_username', '127.0.0.1');";
    $rs     = please_monsieur_db($q);
    if($rs)
        echo "Insert @ " . time() . "\n";
    sleep(rand(2, 8));
    $k++;
}

/*
 * SELECT all attempts in last ninety seconds and for each show the difference
 * between their insertion time and the current time (diff) and 
 * number of seconds left post which the record will be older than 90 secs.
 * Output the status every 2 seconds
 */
$m = 1;
while($m)
{
    $query  = "SELECT *, (NOW() - attempt_time) diff, (90 + attempt_time - NOW()) pending, NOW() nw  FROM failed_login 
            WHERE (username = 'some_username' OR attempt_ip = '127.0.0.1') AND NOW() - attempt_time < 90;";

    $res    = please_monsieur_db($query);

    if(!$res)
        exit;

    $ct     = mysql_num_rows($res);
    echo "\n";
    while($row = mysql_fetch_array($res))
    {
        echo "Now:" . strtotime($row['nw']) . " || Attempt Time: " . strtotime($row['attempt_time']) . 
        " || Diff: [NOW() - attempt_time] = " . $row['diff'] . " || Pending [90-Diff] = : " . $row['pending'] . "\n";
    }
    echo "\n";
    sleep(2);
    $m = $ct;
}
?>

TABLE CODE (如果您需要):

CREATE DATABASE temp_test;
DROP TABLE IF EXISTS failed_login;

CREATE TABLE failed_login (
   attempt_id      INT AUTO_INCREMENT PRIMARY KEY,
   username        VARCHAR(256),
   attempt_ip      VARCHAR(16),
   attempt_time    TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

注意:对于实时输出,请使用命令行运行。

$php -f /path_to_script/script.php  

2 个答案:

答案 0 :(得分:4)

这是因为你正在从mysql日期时间到整数进行隐式转换。

E.g。 mysql认为时间(正如我写的那样)是2011-12-15 13:42:10但是如果我要求mysql从中减去90,它会锻炼20111215134210 - 90 = 20111215134120这是13:41:20这是50几秒钟前。

将时间视为整数(通过转换为/来自unix时间戳,如bankvicar所建议)或使用日期函数对日期值进行数学运算:

SELECT *, 
timediff(NOW(), attempt_time) diff, 
timediff(NOW(), attempt_time + INTERVAL 90 SECONDS) pending,
NOW() nw 
FROM failed_login 
WHERE (username = 'some_username' 
     OR attempt_ip = '127.0.0.1') 
AND NOW() - INTERVAL 90 SECONDS > attempt_time;

(请注意,我还重写了最后一个过滤器表达式,使得表格列在表达式的一侧被隔离 - 当列未被索引时具有较小的速度优势,但在索引时具有巨大的好处)

或者使用秒 - 自 - 纪元......

SELECT *, 
UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(attempt_time) diff, 
UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(attempt_time) + 90 pending,
NOW() nw 
FROM failed_login 
WHERE (username = 'some_username' 
     OR attempt_ip = '127.0.0.1') 
AND UNIX_TIMESTAMP(NOW()) - 90 > UNIX_TIMESTAMP(attempt_time);

(显然无法使用索引优化)。

答案 1 :(得分:1)

我自己测试了这个,我得到了类似的结果。显然,在日期上进行直接算术运算在MySQL中并不一致(实际上是预期的)。您应该使用MySQL日期函数或将日期时间转换为时间戳。我重写了你的查询

SELECT 
   *, 
   (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(attempt_time)) diff, 
   (UNIX_TIMESTAMP(attempt_time) + 90 - UNIX_TIMESTAMP()) pending, 
   NOW() nw  
FROM failed_login 
WHERE (username = 'some_username' OR attempt_ip = '127.0.0.1') 
HAVING diff < 90;

这似乎对我很好。我以2秒的增量迭代到63,没有问题。