2

Here is my code to "store" mysql queries with memcache

$mem = new Memcache;
$mem->connect('127.0.0.1', 11211);

$query = "SELECT * FROM tbl limit 0,20 ";
$key = md5($query);

$get_data = $memcache->get($key);

if($get_data) {
 echo 'Data Pulled From Cache';
} else {
   $res = mysql_fetch_array(mysql_query($query));
   $memcache->set($key, $res, TRUE, 3600); 
}

The problem is that memcache store only the first row returned by query. How to save all 20 rows within one key in memcache ?

2 Answers 2

7

The statement

$res = mysql_fetch_array(mysql_query($query);

only fetches ONE row from the query result.

Try something like this to fetch the entire result before storing it in the cache:

$res = array();
$qres = mysql_query($query);
while($a = mysql_fetch_array($qres, MYSQL_ASSOC))
  $res[] = $a;
mysql_free_result($res);

$memcache->set($key, $res, TRUE, 3600);
Sign up to request clarification or add additional context in comments.

Comments

1

Instead of

$res = mysql_fetch_array(mysql_query($query));
$memcache->set($key, $res, TRUE, 3600);

use mysql_fetch_array() with while, check this

1 Comment

would you mind elaborating the example? i am having a lot of trouble here.. stackoverflow.com/posts/comments/14014953

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.