Reputation: 25
This does not work
$get_data_qry = "SELECT * FROM list;";
$get_data_res = $db->Query($get_data_qry);
$key = 'someKey'; /** silly mistake corrected after being notified by comments*/
$get_data_res = $memcache->get($key);
if ($get_data_res) {
PushOutput($get_data_res);
echo "<br/>Directly from cache";
}
else {
$get_data_res = $db->Query($get_data_qry);
$memcache->set($key, $get_data_res, 0, 20000); /*Store the MySql resource in the cache*/
PushOutput($get_data_res);
}
I get the following message: PHP Warning: Memcache::set() expects parameter 1 to be string, resource given in E:\Repository\HTML\tooldent\songs\songList.tpl on line 54.
It seems weird, why a resource cannot be cached? Any alternatives?
Upvotes: 0
Views: 2907
Reputation: 4108
You just can't cache a resource. The data being cached needs to be serializable:
http://php.net/manual/en/memcache.set.php
Remember that resource variables (i.e. file and connection descriptors) cannot be stored in the cache, because they cannot be adequately represented in serialized state.
You would need to create an array from your data if you want to cache it. Here is a function from my website:
function query_rows_cached($query){
$rowset = $memcache->get(md5($query));
if($rowset){
return $rowset;
}
else{
$r=mysql_fetch_array(mysql_query($q));
$days=1;
$memcache->set(md5($query),$r, false, 60*60*24*$days);
return $r;
}
}
This function works well if the query only returns one row. If your query returns multiple rows, you might have to do some work on the results. Specifically, go through the results and put them in a multidemensional array as talisin says.
Upvotes: 2
Reputation: 594
If your $db construct use mysql_query:
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success.
A resultset is not a string and you set $key to the resultset at line 4.
Update:
$result = $db->query( "SELECT * FROM table" );
$memcache->set(1,$result,TRUE,86400) or die ("Failed to save data");
$cached_result = $memcache->get(1);
var_dump($cached_result);
Output:
object(mysql_result)#2 (0) { }
But as far as I know you can't treat this object as a normal mysql object:
mysql_fetch_assoc($cached_result)
You can try to create a multidimensional array out of the resultset for memcache.
Upvotes: -1