2011-07-03 129 views
0

检查下面的代码,我有以下问题:最后两个参数在SQL语句中是动态的,我怎么可以让memcache获得正确的参数而不仅仅是? ?,只显示我?添加第二个变量$ sql1 =“SELECT id title vtext FROM tpost ORDER BY id desc LIMIT $ var1,$ var2”; ?或者提供更好的解决方案?Memcache&Mysqli准备了语句问题

$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); 

} 

谢谢您的帮助

回答

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); 

} 
0

这是不好的做法,充分利用SQL查询为您的钥匙。创建一个唯一的标识符或至少哈希它。原因在于,随着您扩大您的密钥,他们的匹配速度越慢,数据传输速度也越慢(对于memcache服务器,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);