Several issues here.
First, if memcached can't fetch a key, it returns FALSE not null. You
should be using:
if($results === false)
Second, you can't cache things like database resources, streams, certain
built in objects such as SimpleXML and other things. Think of them as
pointers to other things in memory and when another page is loaded those
contexts are gone.
So, you should store the actual data from your favorite mysql_fetch_*
function, not the mysql resource. You will find an example in another
page you should read:
http://code.google.com/p/memcached/wiki/TutorialCachingStory
(Perhaps to join the mailing list, you should have to answer questions
about that story? hehe, j/k)
And just a pet peeve of mine, lose the die() calls. They are just
clutter. I curse whatever PHP3 examples those originated from.
trigger_error() is a much better solution as it can be handled by an
error_handler and/or logged if the system is so configured.
Brian.
--------
http://brian.moonspot.net/
On 4/16/09 6:11 PM, Paras wrote:
I tried a sample php code which caches a query and then retrieves from
the cache. I am using a mysql table as follows:
ID, name, city, phone
I have a memcached server (128mb) running on the same computer as the
mysql server. (127.0.0.1).
Here is the php code:-
$memcache = new Memcache;
$memcache->connect('127.0.0.1', 11211) or die ("Could not connect to
memcached");
mysql_connect(localhost,$username,$password) or die ("unable to
connect to database!!!");
@mysql_select_db($database) or die( "Unable to select database");
$query='select * from memcached_trial;';
$key = md5($query);
$result = $memcache->get($key);
echo $key;
echo $result;
if($result == null)
{
echo(" ---result not in cache--- ");
$result=mysql_query($query) or die(mysql_error()." : $query");
$memcache->set($key,$result,0,0);
}
$num=mysql_numrows($result);
mysql_close();
the result when I see this in the browser is
d4adc05e7a5dad0e4d5098655acfba440 ---result not in cache--- SELECT *
FROM memcached_trial; ID Name City Phone
1 Erich Giles Princeton 1
2 Craig Miles Deadwood 2
3 Omar Alvarez Harrisburg 3
4 Lionel Prince Pomona 4
5 Cade Love Titusville 5
6 Chester Christian Gainesville 6
7 Xenos Yang Kalispell 7
8 Stone Christensen Calumet City 8
9 Logan Hebert Oneida 9
10 Kasimir Boyle Alexandria 10
Does anyone have any idea why this is happening ?
Thanks
Paras.