Perplexing php / Mysql Time comportamiento aritmético
stoy tratando de SELECCIONAR todas las entradas ingresadas en los últimos noventa segundos y para cada fila obtenida de esta manera:
Mostrar la diferencia entre su tiempo de inserción y el tiempo actual (como diferencia) Muestra el número de segundos que quedan después de que el registro tendrá más de 90 segundos (como pendiente)Estructura de tabla:
attempt_id | username | attempt_ip | attempt_time
Esta es la consulta que estoy 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;
Pero estoy obteniendo resultados inconsistentes:
Prueba de funcionamient
Otra prueba de ejecución
Código completo (si desea probar):
<?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;
}
?>
CÓDIGO DE TABLA (si usted requiere)
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 la salida en tiempo real, ejecute usando la línea de comando.
$php -f /path_to_script/script.php