gpt4 book ai didi

php - Memcache 结果和 while 循环

转载 作者:行者123 更新时间:2023-11-29 23:53:28 25 4
gpt4 key购买 nike

我编写了这个函数来缓存查询:

function get_cached($query, $type = 1) {

$key = md5(strtolower($query));
$cached = $memcache->get($key);

if($cached) {
$res = unserialize($cached);
} else {
$r = mysql_query($query);

if($mode == 1) {
$res = mysql_fetch_object($r);
} else {
$res = mysql_fetch_array($r);
}
$memcache->store($key, serialize($res));
}

return $res;

}

它还不错,我可以缓存简单的查询。但我对在循环内运行的查询有问题。我真的不明白如何解决这个问题,并首先“移植”它以使用我的 get_cached() 函数。

$ref = mysql_query("query");

while($res = mysql_fetch_object($ref)) {

//do something with results

}

如何通过缓存做到这一点?

最佳答案

您无法存储 mysql 结果对象,但可以将所有行提取到数组中并缓存该数组。喜欢

function get_cached($query, $type = 1) {

$key = md5(strtolower($query) . $type);
$cached = $memcache->get($key);

if($cached) {
return unserialize($cached);
} else {
$r = mysql_query($query);
$data = array();

if($mode == 1) {
foreach($row = mysql_fetch_object($r)) {
$data[] = $row;
}
} else {
foreach($row = mysql_fetch_array($r)) {
$data[] = $row;
}
}

$memcache->store($key, serialize($data));
}

return $data;
}

不要忘记将函数的 type 也存储为缓存键,否则您将使用 type==1 获取结果集,作为返回,您将得到元素作为数组

关于php - Memcache 结果和 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25483109/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com