2011-07-03 162 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);