我在 PHP 中做一个数据库类,我想在关联数组中缓存查询结果,我的想法是使用 sql 语句作为缓存数组的索引,这可能是个好主意吗?还是我应该使用 sql 中的 md5?
class DB{
const HOST = 'localhost'; //Your Database Host!
const USER = 'user'; //Your Database Username!
const PASSWORD = 'pass'; //Your Database Password!
const DATABASE = 'database'; //Your Database Name!
private static $Instance;
private static $cache = array();
private function __construct(){
self::$Instance = mysql_connect(self::HOST, self::USER, self::PASSWORD) or die("Could not connect to database server<br/><b>Error:</b>".mysql_error());
mysql_select_db(self::DATABASE) or die("Could not connect to database<br/><b>Error:</b>".mysql_error());
return self::$Instance;
}
public static function DB(){
if(!isset(self::$Instance)){
$c = __CLASS__;
new $c();
}
return self::$Instance;
}
public static function QueryUnique($query){
$query = "$query LIMIT 1";
//$h = md5($query);
$h = $query;
if(isset(self::$cache[$h]))return self::$cache[$h];
$result = mysql_query($query, self::DB());
self::$cache[$h] = mysql_fetch_array($result);
return self::$cache[$h];
}
}
再会