So I’ve got a bunch of database and wordpress querying going on to create a leaderboard.
Querying data, calculating, and then updating seems like a lot to do and really slows the leaderboard display page down. So I’m trying to get the querying and calculating to only happen if it’s been over an hour since the last time it was queried. This is my code so far:
<?php
static $lastQueryTime;
if( !isset($lastQueryTime) || ($now > $lastQueryTime + (60*60)) ){
$lastQueryTime = $now;
//PHP to run...Querying, calculating, updating
}
?>
I’ve also tried “global” instead of “static”, but neither seemed to work, the querying always happens on page load.
PHP code is stateless unless you make it so –
static
variables do not survive across requests, or more precisely nothing does unless you persist it manually.You’ll have to store
$lastQueryTime
on disk or in a database for this to work.static
andglobal
are not mechanisms that persist data across separate instances. They only retain data within a single script run, then all is gone. You need to store the data externally, in a database, a memcache, in a file etc.Write
$lastQueryTime
to a file at the end of you script and include that file at the top if your script. Then test if$lastQueryTime
is over an hour ago. If it is, proceed with your script and save the new time to file. Else, do nothing.