0

I'm trying to use memcache but I'm stuck on a small part. I've got a function that gives in result an array of several things (most of them being strings), and one of them is the result of the mysql_query() function. Here is how I am trying to unserialize:

    $posts_count = my query;                

    /* MEMCACHE KEY GEN*/
    $memcache_key = md5($posts);
    $pagination = memcache_get($memcache, $memcache_key);
    if($pagination==NULL) {
        echo 'NOT CACHED';
        $pagination = (the function that will call mysql_query)
        //SAVE A SERIALIZED VERSION OF THE ARRAY
        $memcache->set($memcache_key, serialize($pagination), 0, 3600); 
    }
    else {
        $pagination = unserialize($pagination);
    }

    //THIS IS ONLY THE RESULT OF mysql_query!!!     

    $posts = $pagination[result]; 
    while($var = mysql_fetch_array($posts)) { ... stuffs here } 

Any idea on how to "save" this result of mysql_query before the mysql_fetch_array? Or any idea how to use memcache to cache the whole while loop?

2
  • 1
    You cannot serialize a resource. End of. Commented Nov 15, 2011 at 0:58
  • Ok, but then is there a way to use memcache in a while loop? Commented Nov 15, 2011 at 1:00

1 Answer 1

1

How about something like this:

$posts_count = "my query";                

/* MEMCACHE KEY GEN*/
$memcache_key = md5($posts);
$pagination = memcache_get($memcache, $memcache_key);
if ($pagination == NULL) {
  echo 'NOT CACHED';
  $pagination = function_that_will_call_mysql_query();
  // Create an array of all the results
  $data = array();
  while ($row = mysql_fetch_assoc($pagination['result'])) {
    $data[] = $row;
  }
  $pagination['result'] = $data;
  //SAVE A SERIALIZED VERSION OF THE ARRAY
  $memcache->set($memcache_key, serialize($pagination), 0, 3600); 
} else {
    $data = unserialize($pagination);
}

// THIS IS ONLY THE RESULT OF mysql_query!!! (but now it's an array)

$posts = $pagination['result']; 
while ($var = array_shift($posts)) {
  // ... do stuff here
} 
Sign up to request clarification or add additional context in comments.

3 Comments

Was going to suggest something similar but the OP is pretty confusing. Hopefully it sticks.
That's perfect! I would never have thought of array_shift ! Thanks a lot ! :)
Hey @DaveRandom Please check out this : stackoverflow.com/questions/9798949/… If you can help...

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.