Problem with mysql result
Mikael Johansson
mikael at synd.info
Sun Jul 30 14:09:38 UTC 2006
mysql_query() returns a PHP resource which is not itself a cachable data type.
To cache the query you could instead read the result set into a temporary array
and then cache that array. Something like:
<?php
$test = $memcache->get('testqry');
if (!$test) {
$qry = "SELECT * from large_db ORDER by ID";
$res = mysql_query($qry) or die(mysql_error());
$test = array();
while ($row = mysql_fetch_array($res)) {
$test[] = $row;
}
$memcache->set('testqry', $test, true, 600)or die("set failed");
}
foreach ($test as $row) {
echo $row['id']." - ".$row['title']." - ".$row['url']."<br>";
}
?>
After the first code block is run, $test should always contain the rows from the
result set which you then can iterate over.
//Mikael
> Hi Guys,
>
> Just starting with memcached and php4 , and i just cant get this to work ,
> all i want is to store the mysql result into memcache for future use , but
> somehow it doesn't work and i can't find any solution googling around...
>
> Maybe someone from this list could help me out ?
>
> It always rreturns as 'not cached' thus hitting the DB .
>
> The code :
>
> <?php
> include_once('../inc/db.inc');
>
> $memcache = new Memcache;
> $memcache->connect('IP', 1211) or die ("Could not connect");
>
> $version = $memcache->getVersion();
> echo "Server's version: ".$version."<br/>\n";
>
> $test = $memcache->get('testqry');
>
> if (!$test) {
>
> $time = microtime();
> $time = explode(" ", $time);
> $time = $time[1] + $time[0];
> $start = $time;
>
> echo "testqry is not cached.<br><Br>";
>
> $qry = "SELECT * from large_db ORDER by ID";
> $res = mysql_query($qry) or die(mysql_error());
>
> while ($row = mysql_fetch_array($res)) {
>
> echo $row['id']." - ".$row['title']." - ".$row['url']."<br>";
>
> }
>
>
> $memcache->set('testqry', $res, true, 600)or die("set failed");
>
> echo "Result stored in cache";
>
> } else {
>
>
>
> echo "testqry was cached.<br><Br>";
>
> $res = $memcache->get('testqry');
>
> echo $res;
>
> }
>
> ?>
>
> Thanks in advance,
>
> Martin
More information about the memcached
mailing list