2012-01-07 39 views
0

隨機結果每次用戶輸入的網站從mysql獲取隨機信息/文本。 問題:如何確保每次用戶刷新頁面時,他/她都會得到與以前相同的不同信息?從mysql每刷新一次(f5)

的第一個想法camed我的腦海裏:

  1. 用戶進入網站,他/她獲得具有$id= '123';
  2. 我們在會話存儲
  3. 用戶再次刷新頁面,ID信息和新的,如果statment執行:
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 
} 

可用於此任何新的方法?

回答

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']; 
+0

可以使用get參數和重定向來代替會話。或者只是一個cookie。 – hakre 2012-01-07 13:20:51

+0

是的,'$ _GET'或'$ _COOKIE'可以工作,但'$ _SESSION'更具防篡改性。 – 2012-01-07 13:30:56

+0

的確,我的評論更多的是作爲一些替代方式。原理與您的答案完全相同,它只是其他形式的* session *。 – hakre 2012-01-07 13:33:06