欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

结合mysql+redis+ajax来简单的获取数据

程序员文章站 2023-03-28 08:00:08
结合mysql+redis+ajax来简单获取数据

结合mysql+redis+ajax来简单获取数据

<?php 
header("content-type:text/html;charset=utf8");
//version 1
$redis = new redis();
$redis->connect('127.0.0.1',6379);
$arr = $redis->get('data_from_class_all');
if(!empty($arr)){
  $data = $arr;
}
else{
  $dsn = "mysql:host=localhost;dbname=demo";
  $db = new pdo($dsn, 'root', '');
  $db->query("set names utf8");
  $data=$db->query('select * from `type`')->fetchall(pdo::fetch_assoc); 
  if(!empty($data)){
    $redis->set('data_from_class_all',$data);
  }
}

//version 2
$data = getdata();
print_r($data);die;


//获取数据
function getdata(){
  // to do somthing...
  $redisobj = getredisinstance();
  $redisdata = getredisstr($redisobj, 'data_from_class_all');
  if(!empty($redisdata)){
    $data = $redisdata;
  }else{
    $db = getmysqlinstance();
    $data = getmysqldataall($db);
    if(!empty($data)){
      setredisstr($redisobj, 'data_from_class_all', serialize($data));
    }
  }


  return $data;
}


// 获取redis实例
function getredisinstance(){
  $redis = new redis();
  $redis->connect('127.0.0.1', 6379);


  return $redis;
}


// 设置redis的string类型值
function setredisstr($redisobj, $rediskey, $data){
  $redisobj->set($rediskey,$data);
}




// 获取redis的string类型值
function getredisstr($redisobj, $rediskey){
  $redisdata = $redisobj->get($rediskey);
  return unserialize($redisdata);
}


// 获取mysql的实例
function getmysqlinstance(){
  $dsn = "mysql:host=localhost;dbname=demo";
  $db = new pdo($dsn, 'root', '');
  $db->query("set names utf8");


  return $db;
}


// 获取mysql的数据
function getmysqldataall($db){
  return $db->query('select * from `type`')->fetchall(pdo::fetch_assoc);
}

?>

<!doctype <html></html>
<html>
<head>
	<link rel="stylesheet" type="text/js" href="./jquery-1.7.2.js">
	<script type="text/javascript" src="./jquery-1.7.2.js"></script>
	<title>分类展示</title>
</head>
<body>
<dl>
<?php for ($i=0; $i <count($data) ; $i++) { ?>
<a onclick="zs('<?php echo $data[$i]['t_id']?>')"><?php echo $data[$i]['title'] ?></a> <br>
<?php } ?>  
</dl>
<span id="box1"></span>
</body>
</html>
<script type="text/javascript">
function zs(id){
	$.ajax({
   type: "post",
   url: "select.php",
   data: "id="+id,
   success: function(msg){
   var box="";
   var jsonreturn = eval("("+msg+")");
   for(var i=0;i<jsonreturn.length;i++){
   		box=box+"<li>";
     for(var key in jsonreturn[i]){
             box=box+jsonreturn[i][key]+"&nbsp;&nbsp;&nbsp;&nbsp;";
     }
     box=box+"</li>";
    }
   $("#box1").html(box);
}
});
}
</script>