mysql从我自己的php函数缓存

时间:2011-07-04 10:20:22

标签: php mysql sql caching

你好:我的功能就像这个

function query($query)
{
    if (in_array($query,$this->queries))
    {
            return $result = $this->results[$query];
    }

    $this->queries[] = $query;
    $result = mysql_query($query);
    if ($result)
    {
            while($row = mysql_fetch_array($result)
            {
                    $this->results[$query][] = $row;
            }

            //I need to return $result for later use (so I can loop it in while if i need to do so later)
            //but problem is that $result is being cleaned up after fetching

    }
}

有人/任何人知道解决方案吗?

2 个答案:

答案 0 :(得分:1)

只要您使用缓冲查询(即mysql_query()而不是mysql_unbuffered_query()),您就可以重置结果集的内部数据指针并使用mysql_fetch _...()重新使用它。 / p>

请参阅http://docs.php.net/function.mysql_data_seek

答案 1 :(得分:1)

您已在函数中获取结果数组,因此不应使用mysql_fetch_assoc。相反,只需循环结果(假设有结果):

function query($query)
{
    if (in_array($query,$this->queries))
    {
        return $result = $this->results[$query];
    }

    $this->queries[] = $query;
    $result = mysql_query($query);
    if ($result)
    {
        while($row = mysql_fetch_assoc($result)
        {
            $this->results[$query][] = $row;
        }

        return $this->results[$query];
    }
}

然后使用:

$result = query("SELECT * FROM test");

if(count($result) > 0)
{
    foreach($result as $key=>$value)
    {
        // Do what you need to with the rows
    }   
}