Perplexing php / Mysql Time comportamento aritmético
Estou tentando selecionar todas as entradas inseridas nos últimos noventa segundos e, para cada linha assim buscada:
Mostrar a diferença entre o horário de inserção e o horário atual (como diff)Mostrar o número de segundos restantes da postagem em que o registro terá mais de 90 segundos (conforme pendente)Estrutura da tabela:
attempt_id | username | attempt_ip | attempt_time
Esta é a consulta que estou usando:
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;
Mas estou obtendo resultados inconsistentes:
Test Run
Outra execução de teste
ódigo completo (se você quiser tenta:
<?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 (se necessário):
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
);
Nota Para saída em tempo real, execute usando a linha de comand
$php -f /path_to_script/script.php