每次用户进入网站时都会从mysql获取随机信息/文本。 问题:如何确保每次用户刷新页面时,他/她得到的信息不同,之前看不到相同的信息?
我想到了第一个想法:
$id= '123';
if ($id == $random_id_from_mysql) {
//select new id from mysql, because it's the same, viewed before
} else {
//show new information and store $id in session for feature usage
}
可用的任何新方法?
答案 0 :(得分:3)
session_start();
// If a value already exists in $_SESSION, it will be used.
// Otherwise, NULL
$prev_rand = isset($_SESSION['prev_rand']) ? $_SESSION['prev_rand'] : NULL;
// Query for a random record that isn't equal to the previous one
// (or isn't NULL if no previous one exists)
// using RAND() and LIMIT 1
$result = mysql_query("SELECT id, col1 FROM tbl WHERE id <> '$prev_rand' ORDER BY RAND() LIMIT 1");
$row = mysql_fetch_array($result);
// Store the new rand value into session
$_SESSION['prev_rand'] = $row['id'];