开发者

mysql caching from my own php function

Hello: I have function like this one

f开发者_StackOverflow社区unction 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

    }
}

does anybody/anyone know solution?


You are already getting an array of the results in the function so you shouldn't use mysql_fetch_assoc. Instead, just loop through the results (assuming there are results):

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

And then use:

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

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


As long as you're using a buffered query (i.e. mysql_query() instead of mysql_unbuffered_query()) you can reset the internal data pointer of the result set and use it (again) with mysql_fetch_...().

see http://docs.php.net/function.mysql_data_seek

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜