php - 从我自己的 php 函数缓存 mysql

标签 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

    }
}

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

最佳答案

您已经在函数中获得了一组结果,因此您不应使用 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
    }   
}

关于php - 从我自己的 php 函数缓存 mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6570143/

相关文章:

php - MediaWiki API - 'opensearch' & 'query' 和 API 调用 url 中的 'generator' & 'list' 有什么区别

php json_encode 仅返回数组的第一行

mysql - 如何为具有多个标签的标签系统创建sql查询?

mysql - 每个用户最多显示3笔交易

php - 如何从不同的类调用我的数据库类

php - ElasticSearch-范围查询不起作用

php - eclipse php 查找已弃用

php - 在 SQL 查询或 PHP 中进行计算?

php - 如何在 SQL 中解析日期?

sql - 如何在我的数据库中执行数据完整性规则?