开发者

Memcache & Mysqli prepared statement problem

check the code below, i have following problem: the last two parameters are dynamic in the SQL statement, how i can make it that memcache gets the right parameters and not only ? ?, which shows me only? Adding a second variable $sql1 = "SELECT id title vtext FROM tpost ORDER BY id desc LIMIT $var1, $var2"; ? Or gives a better solution?

$sql = "SELECT id, title, vtext FROM tpost ORDER BY id desc LIMIT ?, ?";
$content = $memcach开发者_JAVA技巧e->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);

}

Thank you for your help


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

}


It's bad practice to use full SQL queries as your key. Make a unique identifier or at least hash it. The reason is, as you scale up the bigger your key is they slower match and data transfer is (1000r/s to memcache server with small key is faster then the same 1000r/s with a bigger key :)).

Also data can be null, it's not smart to check just on that and fall into SQL query again if user requests an out of bound range.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜