检查下面的代码,我有以下问题:最后两个参数在SQL语句中是动态的,我怎么能让memcache获得正确的参数而不仅仅是? ?,这只显示给我?添加第二个变量$ sql1 =“SELECT id title vtext FROM tpost ORDER BY id desc LIMIT $ var1,$ var2”; ?或者提供更好的解决方案?
$sql = "SELECT id, title, vtext FROM tpost ORDER BY id desc LIMIT ?, ?";
$content = $memcache->get($sql);
if($content == null) {
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('ii', $offset, $rowsperpage);
$stmt->execute();
$stmt->bind_result($r_id, $r_title, $r_vtext);
while ($stmt->fetch()) {
$data[] = array( 'id' => $r_id, 'title' => $r_title, 'vtext' => $r_vtext);
}
$stmt->close();
$memcache->set($sql,$data,0,$cache_time);
}
感谢您的帮助
答案 0 :(得分:1)
$sql = "SELECT id, title, vtext FROM tpost ORDER BY id desc LIMIT ?, ?";
$key = "SELECT id, title, vtext FROM tpost ORDER BY id desc LIMIT $r_title, $r_vtext";
$content = $memcache->get($sql);
if($content == null) {
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('ii', $offset, $rowsperpage);
$stmt->execute();
$stmt->bind_result($r_id, $r_title, $r_vtext);
while ($stmt->fetch()) {
$data[] = array( 'id' => $r_id, 'title' => $r_title, 'vtext' => $r_vtext);
}
$stmt->close();
$memcache->set($key,$data,0,$cache_time);
}
答案 1 :(得分:0)
使用完整的SQL查询作为密钥是不好的做法。创建一个唯一标识符或至少哈希它。原因是,随着你的扩展你的密钥越大,他们的匹配就越慢,数据传输速度就越快(1000r / s到内存服务器,小密钥比1000r / s和更大的密钥更快)。)
此外,数据可以为空,如果用户请求超出范围,则仅检查该数据并且再次陷入SQL查询并不明智。
// Generate key
$key = 'recent:'. $offset .':'. $rowsperpage;
// If nothing found within cache instance, retrieve and set it
if(!$data = $memcache->get($key)) {
$sql = "SELECT `id`, `title`, `vtext`
FROM `tpost`
ORDER BY `id` DESC LIMIT ?, ?";
$stmt = $this->$mysqli->prepare($sql);
$stmt->bind_param('ii', $offset, $rowsperpage);
// Retrieve result set
if($stmt->execute()) {
$data = array();
$stmt->bind_result($r_id, $r_title, $r_vtext);
while ($stmt->fetch()) {
$data[] = array(
'id' => $r_id,
'title' => $r_title,
'vtext' => $r_vtext);
}
}
$stmt->close();
// Set cache entry
$memcache->set($key, $data, 0, $cache_time);