I want to cache my mysql results to decrease database load.
To cache results I am using the following function:
$cached = $this->getMemCacheX($name);
if ($cached === false)
{
$res = mysql_query($query, $con) or die(mysql_error());
if ($res === false) exit('Database failure.');
if ($fetch === "assoc")
{
$data = mysql_fetch_assoc($res);
}
else if ($fetch === "array")
{
$data = mysql_fetch_array($res);
}
if (mysql_num_rows($res) === 0) $data = 0;
$cr = $this->saveMemCacheX($name, $data);
if ($cr === false) exit('Cache failure.');
return $data;
}
else
{
return $cached;
}
My problem is that I need to save and load a result set over wich I used to iterate using a while(mysql_fetch_assoc())-Loop like:
$res = mysql_query("...");
while ($data = mysql_fetch_assoc($res))
{
...
}
Now I need to store my results in the cache, but because I can’t store $res I need to fetch the results first.
How is it possible to iterate through an already fetched result set? I tried out a few foreach-Loops but didn’t find a solution.
How should I fetch the results in order to get an array of associative arrays from the database results?
The mysql_fetch_* functions fetch data one row at a time. They do not return the entire result set. For that, you have to loop over the result set and build your own array: