在mysql_fetch_array之前序列化?

时间:2011-11-15 00:56:11

标签: php mysql serialization memcached

我正在尝试使用memcache,但我只是陷入了一小部分。我有一个函数,它在结果中给出了几个东西的数组(大多数是字符串),其中一个是mysql_query()函数的结果。 以下是我尝试反序列化的方法:

    $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 } 

如何在mysql_fetch_array之前“保存”mysql_query的结果?或者任何想法如何使用memcache缓存整个while循环?

1 个答案:

答案 0 :(得分:1)

这样的事情怎么样:

$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
}