2012-09-19 52 views
0

我有一個小問題在這裏..讓我介紹...Wp的查詢緩存

我有一個腳本來創建一個簡碼..這裏是腳本..

//shortcode stock 
function stok($atts, $content = null) { 
    extract(shortcode_atts(array( 
     "id" => 'http://net.tutsplus.com' 
    ), $atts)); 
    $result = mysql_query("SELECT SUM(quantity) AS value_sum FROM wp_wpsc_cart_contents WHERE prodid = '".$id."'"); 
    $row = mysql_fetch_assoc($result); 
    $stock = '<center><br><b>STOK TERJUAL :</b><div class="nscountdown"><table><thead><tr><td>'.$row['value_sum'].'</td></tr></thead></table></div></center>'; 
    return $stock; 
} 
add_shortcode("stok", "stok"); 

,你可以看到有一個查詢總結列

$result = mysql_query("SELECT SUM(quantity) AS value_sum FROM wp_wpsc_cart_contents WHERE prodid = '".$id."'"); 

羅..問題是..如何緩存的結果,因爲該查詢使我的服務器負載均成爲尖刺...

任何解決方案??

感謝之前....

+0

看起來不像這個查詢應該會導致任何問題。有多少個車可以有一個產品?我建議在該查詢上運行「解釋」,並確保MySQL已正確調整。 - martincho剛剛編輯 – martincho

回答

0

也許Transient API是你所需要的。

function stok($atts, $content = null) { 
    extract(shortcode_atts(array( 
     "id" => 'http://net.tutsplus.com' 
    ), $atts)); 

    if (false === ($query_cache = get_transient(md5($id)))) { 
     $result = mysql_query("SELECT SUM(quantity) AS value_sum FROM wp_wpsc_cart_contents WHERE prodid = '".$id."'"); 
     $row = mysql_fetch_assoc($result); 
     $stock = '<center><br><b>STOK TERJUAL :</b><div class="nscountdown"><table><thead><tr><td>'.$row['value_sum'].'</td></tr></thead></table></div></center>'; 

     // set one hour lifetime cache with the name of md5($id) 
     set_transient(md5($id), $stock, 60*60*1);  
     return $stock; 
    } 
    return $query_cache; 
} 
add_shortcode("stok", "stok"); 
+0

你的代碼不工作......它什麼都沒有返回.. –

+0

仔細檢查你的查詢是否正常。我用一個簡單的字符串測試了它,其中'date()'嵌入了一個很短的生命週期,比如30秒,並且它正在工作。 – Teno

+0

okayy謝謝..它現在的作品.. :) –