每次刷新mysql的随机结果(f5)

时间:2012-01-07 12:52:09

标签: php random

每次用户进入网站时都会从mysql获取随机信息/文本。 问题:如何确保每次用户刷新页面时,他/她得到的信息不同,之前看不到相同的信息?

我想到了第一个想法:

  1. 用户进入网站,他/她获得$id= '123';
  2. 的信息
  3. 我们在会话中存储的ID
  4. 用户再次刷新页面并执行新的if语句:
  5. 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
    }
    

    可用的任何新方法?

1 个答案:

答案 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'];