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('127.0.0.1', 6379); $blog = $redis->get('redisrow'); //如果$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]['title']=$row['title']; $rows[$i]['content']=$row['content']; $i=$i+1; } print_r($rows); $redisrow = json_encode($rows); $redis->setex('redisrow','100',$redisrow); }else{ $redisblog = json_decode($blog); echo "redis"; print_r($redisblog); } ?>
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!