views:

105

answers:

3

Hi How do I select wallpapers randomly, but cache the last selected one for 10 seconds (for performance reasons)?

the faster RAND() function use Cache in wallpapers or image i use this but i need to but cache in image timely change after 1 mins or 5 mins to chnage images in RAND() randoms wallpapers

i use this :

$sql_wallpaper = "SELECT SQL_CACHE * FROM `wallpaper` WHERE wallpaperid >= (SELECT FLOOR( MAX(wallpaperid) * RAND()) FROM `wallpaper` ) ORDER BY wallpaperid LIMIT 0,7";

but i think its not faster ... Need to use cache help me

+2  A: 

a) SQL_CACHE will be ignored, if the query contains RAND()!

b) You will need to save your random id somewhere, e.g. in a database or in apc user data. If using a database you will need to save a timestamp with it, which denotes since then this id is already in use, so you may change it every 5 mins. If using the ladder simply specify a ttl of 5 mins.

nikic
please make a code for me
Hassan
Please make a code for it use like this thats you say...
Hassan
+1  A: 

Assuming PDO & Memcached:

 $pdo; //is the PDO database instance;
 $memcached;//is the memcached instance;

 function _getThe7Wallpapers(){
      global $memcached;
      $cached = $memcached->get('my7wallpapers');
      if($cached!==false) return $cached;
      global $pdo;
      $pdo->query('SELECT COUNT(*) FROM d INTO @count;');
      $pdo->query('SET @stmt = CONCAT(\'SELECT * FROM d ORDER BY id LIMIT \',ROUND(RAND()*GREATEST(@count-7,0)),\',7\');');
      $pdo->query('PREPARE rander FROM @stmt;');
      $rows = $pdo->query('EXECUTE rander;')->fetchAll(PDO::FETCH_ASSOC);
      $memcached->set('my7wallpapers',$rows,300);//cache for 5 minutes
      return $rows;
 }

How to actually set up a PDO instance (or other db-lib) and memcached can be read in the excellent documentation, so I'll leave that up to you as an exercise.

Wrikken
Its great but its Show one Random wallpaper i need to be 7 wallpaper show, how do that? reply must
Hassan
i need it to display LIMIT 0,7 7 random thumbs display How?
Hassan
It will fetch 7 rows, how and when you alter those rows into some html you like is entirely up to you. The `fetchAll` should return 7 rows of data.
Wrikken
its fetchAll but Showing only one record please i need to show 6 or 7 record?how
Hassan
not work properly its show only one record from database problem not solved...
Hassan
Wrikken
ok thanks for help but problem is still finding other way thanks again
Hassan
A: 

simply ORDER BY RAND() in your sql - SELECT * FROM wallpaper ORDER BY RAND() LIMIT 0,7 then cache the results on the PHP side for X time using any of the described methods from other answers

nathan
how can do this please add code for X time
Hassan