I have a php sql
script that generates 5 different values from a database everytime that it executes.
I want those values tot change lets say once a month and not everytime the script runs.
My code is:
$sql = "SELECT * FROM table ORDER BY RAND() LIMIT 5";
$query = mysql_query ($sql, $connection) or die (mysql_error());
while(($row = mysql_fetch_assoc ($query))){
echo "<center>".$row['emri']." ".$row['mbiemri']."</center>";
}
Could anyone help me?
rand(year(now())*100+month(now()))
should give you a different random number every month. The argument for the rand function rand(
...)
is the seed. This value makes the returned random value be the same series, if the seed is the same. The way I wrote it makes the seed be the same each month. (eg this month 201305)
Store the current date in the database. Every time you run the script check whether the current date is 30 days beyond the last stored date and execute accordingly.
Use a cronjob
to schedule a script selecting the random data on the first of the month (0 0 1 * *
), and insert that data either in a separate table, or store it in an internal cache.
Also, you should use array_rand
on the PHP side to randomize in most cases, order by rand()
is a hack which isn't exactly guaranteed to keep working forever (though it probably will because it's been abused so often).
How often will the script be run ?
If it will ONLY be run when you want to change the values then you need to setup a cronjob that will run once a month.
you can make a crontab file in your server to execute a script 'at this time on this date'. See the man page here. May be your server can also use anacrontab.
$sql = "SELECT * FROM table ORDER BY RAND(FLOOR(UNIX_TIMESTAMP()/2592000)) LIMIT 5";
Explanation: if you give rand function a seed (integer parameter) it creates a specific sequence (e.g. RAND(3) always creates the same sequence). Above code gives a different seed every 30 days:
UNIX_TIMESTAMP(): returns seconds since '1970-01-01 00:00:00' UTC
2592000: amount of seconds in 30 days
FLOOR: convert to integer