RedGiant
RedGiant

Reputation: 4748

Caching multiple queries with memcached

What is the way to cache multiple queries with memcached in PHP? Suppose a page takes two queries to render, do I need to use two separate keys and access $memcache twice?

Here's an example:

   $id = $_POST["id"];
   $memcache = new Memcache;
   $memcache->connect('localhost', 11211) or die ("Could not connect");

   $dbh = new PDO("mysql:host=$hostname;dbname=$databasename", $username, $password);
   $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

   $key1 = "{$id}1"; 
   $key2 = "{$id}2"; 

   $cache_result = array();
   $cache_result = $memcache->get($key);
   $cache_result2 = array();
   $cache_result2 = $memcache->get($key2);

   if($cache_result || $cache_result2)
   {
     $rows =$cache_result;
     $rows2 = $cache_result2;
   }
   else
   {
    $sql = "call load_this(?);";
    $users = $dbh->prepare($sql);
    $users->bindValue(1, 1, PDO::PARAM_INT);
    $users->execute();
    $rows = $users->fetchAll(PDO::FETCH_ASSOC);
    $memcache->set($key, $rows, MEMCACHE_COMPRESSED, 1200); 

    $sql = "Call load_that(?)";
    $users = $dbh->prepare($sql);
    $users->bindValue(1, 2, PDO::PARAM_INT);
    $users->execute();
    $rows2 = $users->fetchAll(PDO::FETCH_ASSOC);
    $memcache->set($key2, $rows2, MEMCACHE_COMPRESSED, 1200); 

    print "NOT_CACHED";  
   }

Upvotes: 0

Views: 436

Answers (1)

Dany Caissy
Dany Caissy

Reputation: 3206

You can do it however you want...

If they are going to be cached at the same time, you can also simply do this:

$memcache->set('key', array('result1' => $rows, 'result2' => $rows2), MEMCACHE_COMPRESSED, 1200); 

This would cache both results in the same object and would require less calls to memcached, but the different in performance wouldn't be meaningful.

Upvotes: 1

Related Questions