简体   繁体   中英

PHP - Keep randomized query results for 24 hours

I have a simple query that displays random results, however I'd like to be able to keep those same results for a 24 hour period per visitor so it doesn't randomize on every page refresh. Here's the query:

<?php
$rs1= mysql_query("
SELECT * FROM Table_1
ORDER BY RAND()
LIMIT 4
");
while ($row1= mysql_fetch_array($rs1)) { ?>

I gather I'll need to use the date somehow. I did figure out how to get a random number to show for 24 hours:

<?php
date_default_timezone_set('America/Los_Angeles');
mt_srand(date('Ymd'));
$number = mt_rand(50, 5000);
mt_srand();  //reset for other calls

echo $number;
?>

But I'm not sure how to make that work with my original query. Any ideas? Or should I be creating a cookie rather than trying to do it with only php? How would I make a cookie work with it?

This is a bit CPU intensive if you have to calculate over lot of rows, but do not uses cookies nor any special data to keep selection.

select * from table order by md5(concat(id,curdate())) limit 4

Will show same order on every query on the same day. If want to be diferent based on the user doing the query but still the same on the day, you can add his id to the concat too.

select * from table order by md5(concat(id,userID,curdate())) limit 4

Should be say, that results are no more random and can be predicted by someone that takes the job. You can add a seed too, to mitigate some way this effect.

Pass the date seed that you are using into the query. MySQL's rand() function also takes a seed which would make your random results the same.

http://dev.mysql.com/doc/refman/5.7/en/mathematical-functions.html#function_rand

Here is an example using the mysqli extension since mysql is deprecated.

<?php
date_default_timezone_set('America/Los_Angeles');
mt_srand(date('Ymd'));
$number = mt_rand(50, 5000);

$mysqli = new mysqli("localhost", "user", "password", "database");
$stmt = $mysqli->prepare("SELECT * FROM Table_1 ORDER BY RAND(?) LIMIT 4");
$stmt->bind_param('i', $number);
$stmt->execute();

You could also just do it all in the query

SELECT * FROM Table_1 ORDER BY RAND(CAST(CONCAT(YEAR(), MONTH(), DAY()) AS UNSIGNED)) LIMIT 4

Or whatever seed you want to get from the date.

Save/cache the result to a file (using serialize()) and use the contents of this file to generate your page. Then refresh this file every 24 hours as needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM