开发者

Storing randomly picked rows in session?

开发者 https://www.devze.com 2023-03-22 19:46 出处:网络
Storing randomly picked rows in session? Hi! I’m building a PHP script that outputs a random word from a MySQL table. Each time the script is refreshed I want a new word to display. (It is connecte

Storing randomly picked rows in session?

Hi!

I’m building a PHP script that outputs a random word from a MySQL table. Each time the script is refreshed I want a new word to display. (It is connected to jquery – so the data output of the php-file is directly displayed on my page)

However, I want to display each word only once. If all the words are picked, I want the script to reset and start picking over again.

Right now I have don开发者_JAVA百科e this by setting up an additional table called “visited” and putting all the picked rows from table “wordlist” in there, with the users unique session-id to prevent results from multiple users to interfere with eachother.

So the query goes like this:

session_start();
$id = session_id();

$random_sql = "SELECT *
FROM wordlist AS a
LEFT JOIN visited AS b ON a.word = b.word
AND b.sessionid = '$id'
WHERE b.word IS NULL
ORDER BY a.weight * rand( ) DESC  // Weighted random
LIMIT 1";


$random_row = mysql_query($random_sql);

if(mysql_num_rows($random_row) > 0)
{
while($row = mysql_fetch_row($random_row))
{
$insert_query = "INSERT INTO visited (ID, word, sessionid, date) VALUES ('$row[0]', '$row[1]', '$id', CURDATE())";
$insert = mysql_query($insert_query) or die (mysql_error());
echo $row[1];
}

This works perfectly fine, but I reckon it would be hard for the database to handle many visitors at the same time?

So my question is:

How can I store the information of “visited” words in a session and exclude them from the query?

One more thing: I’m estimating that the wordlist-table will have around 8000 rows. Will this be too many for the ORDER BY RAND-function, and render out to be noticeably slow?

Thanks!


This depends on how much the data must be persistent. If you don't need persistency then session is of course much more efficient in this case. You can store there any PHP data structure, i.e. I guess you'd use associative array in this case.

Regarding performance: if the words are indexed sequentially, you can think of generating the random number as a direct id and just retrieve the particular row directly. ORDER BY RAND() must generate all the numbers and sort them, which is much less efficient than just generate one id like RAND() * MAX(ID).

Read more here.

0

精彩评论

暂无评论...
验证码 换一张
取 消