2011-12-24 29 views
0

我想缓存我的mysql结果以减少数据库负载。 缓存结果我使用下面的函数:缓存并遍历一个关联数组数组

$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; 
} 

我的问题是,我需要保存和载入设定过至极我用用,同时要迭代的结果(mysql_fetch_assoc()) - 循环,如:

$res = mysql_query("..."); 
while ($data = mysql_fetch_assoc($res)) 
{ 
... 
} 

现在我需要将结果存储在缓存中,但因为无法存储$ res,所以我需要首先获取结果。

如何迭代已获取的结果集?我尝试了一些foreach循环,但没有找到解决方案。

我应该如何获取结果以便从数据库结果中获得关联数组的数组?

回答

2

mysql_fetch_ *函数一次获取一行数据。他们不返回整个结果集。为此,您必须遍历结果集并构建您自己的数组:

$data = array(); 
while($row = mysql_fetch_assoc($result)) { // fetch as an associative array 
    $data[] = $row; 
}