Caching Queries & Result without Rerun Database

Problem:- Caching Queries & Result without Rerun Database

Solution:-

Download Cache Lite PEAR Package

<?php 

require 'Cache/Lite.php';

$opts = array(
		'cacheDir'=> 'Cache',
		'automaticSerialization'=>true,
		'lifeTime'=>600

);
$cache = new Cache_lite($opts);

$db = new PDO("mysql:host=localhost; dbname=testdb", 'root', '');

$sql = "SELECT * FROM data WHERE name = ?";
$param = array($_GET['name']);
$key = cache_key($sql, $param);
$result = $cache->get($key);

if ($result=== false) {
	$stmt = $db->prepare($sql);
	$stmt->execute($param);
	$result = $stmt->fetchAll();
	$cache->save($result);
}

foreach ($result as $value) {
	print $value['id'] . ' : '. $value['name']. ' => ' . $value['mobile'].'<br>'; 
}

function cache_key($sql, $param){
	return md5($sql,
		implode(" | ", array_keys($param)) . implode(' | ', $param) 

	);
}

 ?>

 

Be the first to comment

Leave a Reply

Your email address will not be published.


*