Memcache和Mysqli准备声明问题

时间:2013-02-04 15:31:13

标签: php mysqli memcached

这让我很疯狂,问题是我无法解决如何获取并设置要在我的视图中显示的缓存数据。

public function get_something($id, $account_name)
{
    $sql = "SELECT one,two,three FROM table WHERE id = ? and account_name = ? ";
    $key = md5("SELECT one,two,three FROM table WHERE id = $id and account_name = $account_name ");

    $get_result = $this->Core->Core->Memcache->get($key);

    if($get_result)
    {
      // How would I set the Data
    }
    else
    {
     $stmt = $this->Core->Database->prepare($sql);
     $stmt->bind_param("is", $id, $account_name);
     $stmt->execute();
     $stmt->store_result();
     $stmt->bind_result($one, $two, $three);
     $stmt->fetch();
     //Below is how i set the data
     $this->Core->Template->set_data('one', $one);  
     //Set the Memcache
     $this->Core->Memcache->set($key, $stmt, TRUE, 20);
}

所以我的问题是如何从memcache中的预处理语句获取和设置数据?

1 个答案:

答案 0 :(得分:0)

Memcache是​​一个键/值存储系统,其密钥和值都需要序列化。来自php.net页面:

  

请记住,资源变量(即文件和连接描述符)不能存储在缓存中,因为它们无法在序列化状态下充分表示。

您的sql语句似乎在一行中查找三个值。我不是mysqli的专家,但这是你想做的事情:

public function get_something($id, $account_name){
  $sql = "SELECT one,two,three FROM table WHERE id = ? and account_name = ? ";
  $key = md5("SELECT one,two,three FROM table WHERE id = $id and account_name = $account_name ");

  $get_result = $this->Core->Core->Memcache->get($key);

  if($get_result){
    return $get_result;//#1 just return it, the format is an array like what is being built below
  }
  else{
   $stmt = $this->Core->Database->prepare($sql);
   $stmt->bind_param("is", $id, $account_name);
   $stmt->execute();
   $stmt->store_result();
   $stmt->bind_result($one, $two, $three);
   $stmt->fetch();
   //Below is how i set the data
   $this->Core->Template->set_data('one', $one);//#2 I don't know what this line does or is for, presumably for something else besides memcache stuff, maybe it acts like return
   //Set the Memcache
   $array=array();//#3
   $array[]=$one;
   $array[]=$two;
   $array[]=$three;

   $this->Core->Memcache->set($key, $array, TRUE, 20);
   //this is a function, do you want to return your values somewhere?
 }

一些注意事项,#1问题的答案很简单,只需返回$get_result即可。它应该是一个包含三个值的数组。 #2我不熟悉这条线,也不熟悉它。这是你将值“返回”到控制器的方式吗?如果是这样,你会想要模仿我将return置于if#3内的那一行。这是你的问题。你不能在memcache中保存$stmt变量,它是一个mysqli对象,而不是你想要的数据。您需要构建一个数组,然后保存该数组。那应该为你做。

还有其他细微差别,您可以循环返回值。你应该检查mysql没有返回任何东西。但这是实现这一目标的基本出发点。

请告诉我这是否适合您。