簡體   English   中英

Memcache & Mysqli 准備語句問題

[英]Memcache & Mysqli prepared statement problem

檢查下面的代碼,我有以下問題: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);

}

謝謝您的幫助

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

}

使用完整的 SQL 查詢作為密鑰是不好的做法。 制作一個唯一標識符或至少 hash 它。 原因是,當您擴大密鑰時,它們的匹配速度會變慢,並且數據傳輸速度會變慢(1000r/s 到 memcache 服務器的小密鑰比相同的 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM