从数据库中检索并回显随机项,并继续回显五秒钟

时间:2013-03-11 00:20:48

标签: php mysql

以下程序就是这样做的!

<?php
/************************************
AIM: To retrieve and echo a random item from a database, and continue to echo the same item whenever and whereever the page is reloaded, for five seconds. After the five seconds is up, the program must echo another random item, and contine ad infinitum.
CONDITIONS: The program cannot echo two results in a row. (In effect the same result for ten seconds).
*************************************/
// Get ready to seed a random value from future 'rand()' function. Seed for 5 seconds.
srand(floor(time() / (5)));

// Retreieve all rows from table 'dogs'.
$result1 = $mysqli->query = new mysqli("SELECT * FROM dogs", MYSQLI_USE_RESULT);

// See how many rows are in 'dogs'.
mysqli_result::$num_rows;

// Generate a random value between 1 and the number of rows in 'dogs'.
echo $random = rand(1,$num_rows) . '<br>';

// Find the current date as a unix timestamp.
echo $currentdate = time() . '<br>';

// Find the time ten seconds ago.
echo $datetensecondsago = $currentdate - 10;
echo '<br>';

?>

然而,我不知道如何让它不连续两次回应相同的随机数据库项目!

数据库原理图如下:

Table Name = dogs
id  |  name  |  lastused
------------------------
1   |  Rover |  1362960167
2   |  Chip  |  1362960123
3   |  Rex   |  1362960178

我认为答案在于mysql查询,例如

SELECT * FROM dogs WHERE dateused<$datetensecondsago LIMIT 1

然后更新已使用项目的时间,但我无法完成它!

感谢帮助!

1 个答案:

答案 0 :(得分:0)

您可以将随机行保存在会话变量中(即使您重新加载页面也是可访问的(并且会话未过期)。)

 session_start();
 // store session data
 $_SESSION['my_variable'] = 'something';

然后你可以检查一个元素是否已被回显,或者(更好)你可以用SQL中的WHERE子句将其排除在外: SELECT ... FROM ... WHERE id <> LAST_ID(宽度LAST_ID =最后一个回显元素的id)。


您可以使用SELECT COUNT(*) FROM table来检索mysql表中的行数。


有一种更简单的方法可以从表中获取随机行:

SELECT * FROM table ORDER BY RAND() LIMIT 1

还有类似但更快的方法(如果只是谷歌 mysql随机感兴趣的话)


您是否考虑使用javascript甚至AJAX?
使用javascript,不需要页面重新加载来更改其内容。