0

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";  
   }
3
  • "do I need to use two separate keys and access $memcache twice" --- it depends. Do you want to store them separately or together? Commented Nov 4, 2014 at 21:59
  • @zerkms I need to loop over rows and `rows2´ separately, so I guess I can't store them in one key. Commented Nov 4, 2014 at 22:04
  • 1
    you can. Just put them in a single array Commented Nov 4, 2014 at 22:10

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thak you. I will try it out. How should I fetch the data? $memcache->get('result1'); ?
No, you will use one key, in my example, it would be get('key'); This would return an array containing both your results.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.