PHP implements the method of querying mysql and caching it to redis

小云云
Release: 2023-03-22 21:58:02
Original
3579 people have browsed it

This article mainly shares with you the method of querying mysql in php and caching it to redis. I hope it can help you.

First install redis and enable the php_redis extension in the php environment.

No more to say below, just go to the code

<?php 
$redis = new redis();
$redis->connect(&#39;127.0.0.1&#39;, 6379);
$blog = $redis->get(&#39;redisrow&#39;);
//如果$blog数组为空,则去数据库中查询,并加入到redis中
if(empty($blog)){
	echo "mysql";
	// Connect mysql server
	$mysql = new PDO("mysql:host=localhost;dbname=blog","root","",array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")); 
	$rs = $mysql -> query("select * from tbl_post");
	//$row = $rs -> fetch();
	$i=0;
	while($row = $rs -> fetch()){
		$rows[$i][&#39;title&#39;]=$row[&#39;title&#39;];
		$rows[$i][&#39;content&#39;]=$row[&#39;content&#39;];
		$i=$i+1;
	}
	print_r($rows);
	$redisrow = json_encode($rows);
	$redis->setex(&#39;redisrow&#39;,&#39;100&#39;,$redisrow);
}else{
	$redisblog = json_decode($blog);
	echo "redis";
	print_r($redisblog);
}
?>
Copy after login

Related recommendations:

How to query MySQL concurrently with PHP

php concurrency example about querying MySQL (picture)

Three common methods for php to access and query mysql data

The above is the detailed content of PHP implements the method of querying mysql and caching it to redis. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!