2011-07-03 8 views
0

以下のコードを確認してください。最後の2つのパラメータはSQL文の中で動的です。どのようにしてmemcacheが正しいパラメータを取得できるのですか? ?私だけを示していますか? 2番目の変数を追加する$ sql1 = "SELECT id title vtext FROM tpost ORDER BY id desc LIMIT $ var1、$ var2"; ?または、より良い解決策を提供しますか?Memcache&Mysqli prepared statement問題

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

} 

それはあなたのキーとして完全なSQLクエリを使用することは悪い習慣だあなたの助け

答えて

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

、ありがとうございました。一意の識別子を作成するか、少なくともそれをハッシュします。理由は、鍵を大きくするにつれて、鍵のサイズが小さくなり、データ転送が遅くなる(小さな鍵を持つMemcacheサーバには1000r/sが、より大きい鍵では1000r/sが速くなります:))。

また、データはnullでもかまいません。ちょうどそれをチェックして、ユーザーが範囲外の範囲を要求した場合に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); 
関連する問題