我正在运行一个从 MySQL 表中提取数据的 php 脚本。我将在经常访问的服务器上运行它,并希望将数据在缓存中保留 X 时间。所以一旦你拉了它,数据就会保存在服务器上,而时间还没有过去。这是脚本:
<?php
include('mysql_connection.php');
$c = mysqlConnect();
$locale = $_GET['locale'];
$last_news_id = $_GET['news_id'];
sendQuery ("set character_set_results='utf8'");
sendQuery ("set collation_connection='utf8_general_ci'");
if(strcmp($locale,"ru") != 0)
$locale = "en";
$result = sendQuery("SELECT * FROM news WHERE id > ".$last_news_id." and locale = '".$locale."' ORDER BY id DESC LIMIT 10");
echo '<table width=\"100%\">';
while($row = mysqli_fetch_array($result, MYSQL_NUM))
{
echo '<tr><td width=\"100%\"><b>Date: </b>'.$row[2].'</td></tr>';
echo '<tr><td width=\"100%\">'.preg_replace('/#([^#]*)#(.*)/', ' <a href="$2" target="_blank">$1</a>', $row[3]).'</td></tr>';
echo '<tr><td width=\"100%\"><hr style="height: 2px; border: none; background: #515151;"></td></tr>';
}
echo '</table>';
mysqliClose($c);
?>
使用什么 php 函数来缓存数据?什么是最好的方法?谢谢!
最佳答案
您可以使用 php 内存缓存: 只需在脚本中的“sendQuery()”函数之后添加此代码并将其存储在缓存中,如下所示:
$memcache_obj = memcache_connect('memcache_host', 11211);
memcache_set($memcache_obj, 'var_key', $result, 0, 30);
echo memcache_get($memcache_obj, 'var_key');
关于php - 为 php mysql 查询创建缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14055287/