基于mysql的仿memcache缓存类
Jun 07, 2016 pm 04:39 PM当年在sae的时候,内置的mysql类用得挺舒服的。后来自己简单封装了下,runSql方法执行的sql语句,getData方法取得结果数组,Transactions方法实现事务。 mysql = new FaMysql(); } function set($key,$value,$expire = 31536000){//默认有效期一年 $now = ti
当年在sae的时候,内置的mysql类用得挺舒服的。后来自己简单封装了下,runSql方法执行的sql语句,getData方法取得结果数组,Transactions方法实现事务。 mysql = mysql_connect($options['host'],$options['username'],$options['password']) or die ("Database connection error."); mysql_select_db($options['database'],$this->mysql); mysql_query("set names '" . $options['charset'] . "'"); } public function Transactions(array $sql){ mysql_query("BEGIN"); $r = 1; foreach($sql as $key => $row) { $res = mysql_query($row); if(!$res) {$r = 0;} } if(!$r){mysql_query("ROLLBACK");}else{mysql_query("COMMIT");} mysql_query("END"); } public function runSql($sql){ mysql_query($sql) or die(mysql_error()); } public function getData($sql){ $result = mysql_query($sql) or die(mysql_error()); $array = array(); while($row = mysql_fetch_assoc($result)) { $array[] = $row; } return $array; } } 刚开始没买vps,RP主机又不提供memcache缓存,所以自己实现的这么个玩意。set方法存储数据,get方法获取数据,del方法删除数据,都只支持string哦。 class FaMemcache{ private $mysql; private $TABLENAME = 'memcache'; public function __construct(){ $this->mysql = new FaMysql(); } function set($key,$value,$expire = 31536000){//默认有效期一年 $now = time(); $valid = $now + $expire; $data = $this->mysql->getData("SELECT Fa_key FROM `$this->TABLENAME` WHERE Fa_key = '$key'"); if(count($data)!=0){ $this->mysql->runsql("UPDATE `$this->TABLENAME` SET Fa_value = '$value',Valid = '$valid' WHERE Fa_key = '$key'"); }else{ $this->mysql->runsql("INSERT INTO `$this->TABLENAME` (Fa_key,Fa_value,Valid) VALUES ('$key','$value','$valid')"); } } function get($key){ $now = time(); $data = $this->mysql->getData("SELECT Fa_value FROM `$this->TABLENAME` WHERE Fa_key = '$key' AND $now > Valid"); if(count($data)!=0){ return $data[0]['Fa_value']; }else{ return null; } } function del($key){ $this->mysql->runsql("DELETE FROM `$this->TABLENAME` WHERE Fa_key = '$key'"); } }原文地址:基于mysql的仿memcache缓存类, 感谢原作者分享。

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP's big data structure processing skills

How to optimize MySQL query performance in PHP?

How to use MySQL backup and restore in PHP?

How to insert data into a MySQL table using PHP?

How to fix mysql_native_password not loaded errors on MySQL 8.4

How to use MySQL stored procedures in PHP?

Caching mechanism and application practice in PHP development

How to create a MySQL table using PHP?
