PDO支持数据缓存

 更新时间:2016年11月25日 16:31  点击:2064

/**
 * 作者:初十
 * QQ:345610000
 */
class myPDO extends PDO
{
 public $cache_Dir = null; //缓存目录
 public $cache_expireTime = 7200; //缓存时间,默认两小时
 
 //带缓存的查询
 public function cquery($sql)
 {
  //缓存存放总目录
  if ($this->cache_Dir == null || !is_dir($this->cache_Dir)) {
   exit ("缓存目录有误!");
  } else {
   $this->cache_Dir = str_replace("\", "/", $this->cache_Dir);
   $FileName = trim($this->cache_Dir, "/") . '/' . urlencode(trim($sql)) . '.sql';
  }
  //判断生成缓存
  if (!file_exists($FileName) ||  time() - filemtime($FileName) > $this->cache_expireTime) {
   if ($tmpRS = parent::query($sql)) {
    $data = serialize($tmpRS->fetchAll());
    self::createFile($FileName, $data);
   } else  {
    exit ("SQL语法错误<br />");
   }
  }
  return $this->readCache($FileName);
 }
 
 //读缓存文件
 private static function readCache($FilePath)
 {
  if (is_file($FilePath) && $Data = file_get_contents($FilePath)) {
   return new cache_PDOStatement(unserialize($Data));
  }
  return false;
 }
 
 //生成文件
 public static function createFile($FilePath, $Data = '')
 {
  if (file_put_contents($FilePath, $Data)) {
   return true;
  } else {
   return false;
  }
 }
}
//缓存用到Statement类
class cache_PDOStatement
{
 private $recordArr = array();
 private $cursorId = 0;
 private $recordCount = 0;
 
 public function __construct($arr)
 {
  $this->recordArr = $arr;
  $this->recordCount = count($arr);
 }
 
 //返回一条记录,指针下移一行
 public function fetch()
 {
  if ($this->cursorId == $this->recordCount) {
   return false;
  } else if ($this->cursorId == 0) {
   $this->cursorId++;
   return current($this->recordArr);
  } else {
   $this->cursorId++;
   return next($this->recordArr);
  }
 }
 
 //返回全部结果
 public function fetchAll()
 {
  return $this->recordArr;
 }
 
 //单行单列查询
 public function fetchColumn()
 {
  $tmpArr = current($this->recordArr);
  return $tmpArr[0];
 }
}

使用方法
$db = new myPDO('mysql: host = localhost;dbname=news','newsadmin','123456');

$db->cache_Dir = "cache"; //设置缓存目录
$db->cache_expireTime = 7200; //设置缓存时间

$rs = $db->cquery("select * from news limit 0,10"); //用缓存查询方法cquery代替query
while ($row = $rs->fetch()) {
 echo $row["F_title"] . "<br />";
}

$rs = null;
$db = null;

<?php


class mysql
{
 var $host     = "";   //mysql主机名
 var $user     = "";   //mysql用户名
 var $pwd      = "";   //mysql密码
 var $dbName   = "";   //mysql数据库名称
 var $linkID   = 0;   //用来保存连接ID
 var $queryID  = 0;   //用来保存查询ID
 var $fetchMode= MYSQL_ASSOC;//取记录时的模式
 var $queryTimes = 0;  //保存查询的次数
 var $errno    = 0;   //mysql出错代号
 var $error    = "";   //mysql出错信息
 var $record   = array(); //一条记录数组

 //======================================
 // 函数: mysql()
 // 功能: 构造函数
 // 参数: 参数类的变量定义
 // 说明: 构造函数将自动连接数据库
 //       如果想手动连接去掉连接函数
 //======================================
 function mysql($host,$user,$pwd,$dbName)
 { if(empty($host) || empty($user) || empty($dbName))
   $this->halt("数据库主机地址,用户名或数据库名称不完全,请检查!");
  $this->host    = $host;
  $this->user    = $user;
  $this->pwd     = $pwd;
  $this->dbName  = $dbName;
  $this->connect();//设置为自动连接
 }
 //======================================
 // 函数: connect($host,$user,$pwd,$dbName)
 // 功能: 连接数据库
 // 参数: $host 主机名, $user 用户名
 // 参数: $pwd 密码, $dbName 数据库名称
 // 返回: 0:失败
 // 说明: 默认使用类中变量的初始值
 //======================================
 function connect($host = "", $user = "", $pwd = "", $dbName = "")
 {
  if ("" == $host)
   $host = $this->host;
  if ("" == $user)
   $user = $this->user;
  if ("" == $pwd)
   $pwd = $this->pwd;
  if ("" == $dbName)
   $dbName = $this->dbName;
  //now connect to the database
  $this->linkID = mysql_pconnect($host, $user, $pwd);
  if (!$this->linkID)
  {
   $this->halt();
   return 0;
  }
  if (!mysql_select_db($dbName, $this->linkID))
  {
   $this->halt();
   return 0;
  }
  return $this->linkID;   
 }
 //======================================
 // 函数: query($sql)
 // 功能: 数据查询
 // 参数: $sql 要查询的SQL语句
 // 返回: 0:失败
 //======================================
 function query($sql)
 {
  $this->queryTimes++;
  $this->queryID = mysql_query($sql, $this->linkID);
  if (!$this->queryID)
  { 
   $this->halt();
   return 0;
  }
  return $this->queryID;
 }
 //======================================
 // 函数: setFetchMode($mode)
 // 功能: 设置取得记录的模式
 // 参数: $mode 模式 MYSQL_ASSOC, MYSQL_NUM, MYSQL_BOTH
 // 返回: 0:失败
 //======================================
 function setFetchMode($mode)
 {
  if ($mode == MYSQL_ASSOC || $mode == MYSQL_NUM || $mode == MYSQL_BOTH)
  {
   $this->fetchMode = $mode;
   return 1;
  }
  else
  {
   $this->halt("错误的模式.");
   return 0;
  }
  
 }
 //======================================
 // 函数: fetchRow()
 // 功能: 从记录集中取出一条记录
 // 返回: 0: 出错 record: 一条记录
 //======================================
 function fetchRow()
 {
  $this->record = mysql_fetch_array($this->queryID,$this->fetchMode);
  return $this->record;
 }
 //======================================
 // 函数: fetchAll()
 // 功能: 从记录集中取出所有记录
 // 返回: 记录集数组
 //======================================
 function fetchAll()
 {
  $arr = array();
  while($this->record = mysql_fetch_array($this->queryID,$this->fetchMode))
  {
   $arr[] = $this->record;
  }
  mysql_free_result($this->queryID);
  return $arr;
 }
 //======================================
 // 函数: getValue()
 // 功能: 返回记录中指定字段的数据
 // 参数: $field 字段名或字段索引
 // 返回: 指定字段的值
 //======================================
 function getValue($field)
 {
  return $this->record[$field];
 }
 //======================================
 // 函数: affectedRows()
 // 功能: 返回影响的记录数
 //======================================
 function affectedRows()
 {
  return mysql_affected_rows($this->linkID);
 }
 //======================================
 // 函数: recordCount()
 // 功能: 返回查询记录的总数
 // 参数: 无
 // 返回: 记录总数
 //======================================
 function recordCount()
 {
  return mysql_num_rows($this->queryID);
 }
 //======================================
 // 函数: getQueryTimes()
 // 功能: 返回查询的次数
 // 参数: 无
 // 返回: 查询的次数
 //======================================
 function getQueryTimes()
 {
  return $this->queryTimes;
 }
 //======================================
 // 函数: getVersion()
 // 功能: 返回mysql的版本
 // 参数: 无
 //======================================
 function getVersion()
 {
  $this->query("select version() as ver");
  $this->fetchRow();
  return $this->getValue("ver");
 }
 //======================================
 // 函数: getDBSize($dbName, $tblPrefix=null)
 // 功能: 返回数据库占用空间大小
 // 参数: $dbName 数据库名
 // 参数: $tblPrefix 表的前缀,可选
 //======================================
 function getDBSize($dbName, $tblPrefix=null)
 {
  $sql = "SHOW TABLE STATUS FROM " . $dbName;
  if($tblPrefix != null) {
   $sql .= " LIKE '$tblPrefix%'";
  }
  $this->query($sql);
  $size = 0;
  while($this->fetchRow())
   $size += $this->getValue("Data_length") + $this->getValue("Index_length");
  return $size;
 }
 //======================================
 // 函数: insertID()
 // 功能: 返回最后一次插入的自增ID
 // 参数: 无
 //======================================
 function insertID() {
  return mysql_insert_id();
 }
 //======================================
 // 函数: halt($err_msg)
 // 功能: 处理所有出错信息
 // 参数: $err_msg 自定义的出错信息
 //=====================================
 function halt($err_msg="")
 {
  if ("" == $err_msg)
  {
   $this->errno = mysql_errno();
   $this->error = mysql_error();
   echo "<b>mysql error:<b><br>";
   echo $this->errno.":".$this->error."<br>";
   exit;
  }
  else
  {
   echo "<b>mysql error:<b><br>";
   echo $err_msg."<br>";
   exit;
  }
 }
}
?>


<?php
$msn = new myMSN("h058@test.com", "123");
// MSNv9

class myMSN
{
private $server = "messenger.hotmail.com";
private $port = 1863;
private $nexus = "https://nexus.passport.com/rdr/pprdr.asp";
private $sshLogin = "login.live.com/login2.srf"; //loginnet.passport.com/login2.srf
private $getCode = null;
private $_ip = null;
private $_port = null;
private $connect = null;
private $trID = 1;
private $maxMessage = 4096;
private $userName = null;
private $passWord = null;
private $debug = true;
function myMSN($userName="", $passWord="")
{
if (!empty($userName) && !empty($passWord))
{
$this->userName = $userName;
//$this->passWord = urlencode($passWord);
$this->passWord = $passWord;
$this->startTalk();
}
}

function put($data)
{
if ($this->isConnect())
{
fputs($this->connect, $data);
$this->trID++;
if ($this->debug)
print("<div style='color:green;font-size:13px;'>&gt;&gt;&gt;{$data}</div>");
}
}
function get()
{
if ($data = @fgets($this->connect, $this->maxMessage))
{
if ($this->debug)
print("<div style='color:red;font-size:13px;'>&lt;&lt;&lt;{$data}</div>");
return $data;
}
else
{
return false;
}
}
function isConnect()
{
if (!is_null($this->connect))
return true;
else
return false;
}
function close()
{
@fclose($this->connect);
}
function startTalk()
{
if ($this->connect = fsockopen($this->server, $this->port, $errno, $errstr, 2))
$this->verTalk();
}

function verTalk() // MSN 协议协商
{
$this->put("VER {$this->trID} MSNP9 CVR0 rn");
$data = $this->get();
//echo $data;
if (false !== strripos($data, "VER"))
$this->envTalk();
}
function envTalk() // 环境协商
{
$this->put("CVR {$this->trID} 0x0409 winnt 5.0 i386 MSNMSGR 7.0.0816 MSMSGS {$this->userName} rn");
$data = $this->get();
//echo $data;
if (false !== strripos($data, "CVR"))
$this->reqTalk();
}
function reqTalk() // 请求确认
{
$this->put("USR {$this->trID} TWN I {$this->userName} rn");
$data = $this->get(); // XFR 3 NS 207.46.107.41:1863 0 65.54.239.210:1863 XFR 3 NS 207.46.107.25:1863 U D
//echo $data;
if (false !== strripos($data, "XFR"))
{
list(, , , $serv) = explode(" ", $data); // 分析服务器
list($ip, $port) = explode(":", $serv); // 分析IP和端口
$this->_ip = $ip;
$this->_port = $port;
$this->reLink($ip, $port);
}
else
{
//echo $data; // USR 3 TWN S ct=1205292058,rver=5.0.3270.0,wp=FS_40SEC_0_COMPACT,lc=1033,id=507,ru=http:%2F%2Fmessenger.msn.com,tw=0,kpp=1,kv=4,ver=2.1.6000.1,rn=1lgjBfIL,tpf=b0735e3a873dfb5e75054465196398e0
list(, , , , $this->getCode) = explode(" ", trim($data));
//echo $data;
if (empty($this->sshLogin))
$this->reLoginTalk(); // 重新获取登陆服务器地址
else
$this->getLoginCode($this->sshLogin);
}
}
function reLink($server, $port) // 重置连接
{
$this->connect = null;
$this->server = $server;
$this->port = $port;
$this->trID = 1;
$this->startTalk();
}
function reLoginTalk() // 重新获取服务器地址
{
$ch = curl_init($this->nexus);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$header = curl_exec($ch);
//print_r($header);
curl_close($ch);
preg_match ('/DALogin=(.*?),/', $header, $out); // 捕捉服务器登陆匹配
//print_r($out);
if (isset($out[1]))
{
$this->getLoginCode($out[1]);
}
else
{
//return false;
exit("无法捕捉到登陆服务器的URL");
}
}
function getLoginCode($slogin) // 获取登陆代码
{
//echo($this->getCode);
if (!is_null($this->getCode))
{
$ch = curl_init("https://" . $slogin);
$loginInfo = array(
"Authorization: Passport1.4 rgVerb=GET,OrgURL=http%3A%2F%2Fmessenger%2Emsn%2Ecom,sign-in=" . $this->userName . ",pwd=" . $this->passWord . "," . $this->getCode,
"Host: login.passport.com"
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $loginInfo);
//print_r($loginInfo);
//$this->getCode = null;
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$header = curl_exec($ch);
//print_r($header);
preg_match ("/from-PP='(.*?)'/", $header, $out);
//print_r($out);
if (isset($out[1]))
{
$this->loginAction($out[1]);
}
else
{
//return false;
exit("无法捕捉到登陆代码的信息");
}
}
else
{
return false;
}
}
function loginAction($loginCode) // 登陆工作
{
$this->put("USR {$this->trID} TWN S {$loginCode} rn"); // USR |trID| SSO S |t=code|
$data = $this->get();
//echo $data;
//print_r($data);
//$this->put("SYN {$this->trID} 0 rn");
//$this->put("CHG {$this->trID} NLN rn");
//print_r($this->get());
}
}

?>
 

<?php
header("Content-type: text/html;charset=GBK");//输出编码,避免中文乱码
?>
<html>
<head>
<title>ajax分页演示</title>
<script language="javascript" src="ajaxpg.js"></script>
</head>
<body>
<div id="result">
<?php
$page=isset($_GET['page'])?intval($_GET['page']):1;        //这句就是获取page=18中的page的值,假如不存在page,那么页数就是1。
$num=10;                                      //每页显示10条数据

$db=mysql_connect("localhost","root","7529639");           //创建数据库连接
mysql_select_db("cr_download");                 //选择要操作的数据库

/*
首先咱们要获取数据库中到底有多少数据,才能判断具体要分多少页,具体的公式就是
总数据库除以每页显示的条数,有余进一。
也就是说10/3=3.3333=4 有余数就要进一。
*/

$result=mysql_query("select * from cr_userinfo");
$total=mysql_num_rows($result); //查询所有的数据

$url='test.php';//获取本页URL

//页码计算
$pagenum=ceil($total/$num);                                    //获得总页数,也是最后一页
$page=min($pagenum,$page);//获得首页
$prepg=$page-1;//上一页
$nextpg=($page==$pagenum ? 0 : $page+1);//下一页
$offset=($page-1)*$num;                                        //获取limit的第一个参数的值,假如第一页则为(1-1)*10=0,第二页为(2-1)*10=10。

//开始分页导航条代码:
$pagenav="显示第 <B>".($total?($offset+1):0)."</B>-<B>".min($offset+10,$total)."</B> 条记录,共 $total 条记录 ";

//如果只有一页则跳出函数:
if($pagenum<=1) return false;

$pagenav.=" <a href=javascript:dopage('result','$url?page=1');>首页</a> ";
if($prepg) $pagenav.=" <a href=javascript:dopage('result','$url?page=$prepg');>前页</a> "; else $pagenav.=" 前页 ";
if($nextpg) $pagenav.=" <a href=javascript:dopage('result','$url?page=$nextpg');>后页</a> "; else $pagenav.=" 后页 ";
$pagenav.=" <a href=javascript:dopage('result','$url?page=$pagenum');>尾页</a> ";
$pagenav.="</select> 页,共 $pagenum 页";

//假如传入的页数参数大于总页数,则显示错误信息
If($page>$pagenum){
       Echo "Error : Can Not Found The page ".$page;
       Exit;
}

$info=mysql_query("select * from cr_userinfo limit $offset,$num");   //获取相应页数所需要显示的数据
While($it=mysql_fetch_array($info)){
       Echo $it['username'];
       echo "<br>";
}                                                              //显示数据
  echo"<br>";
  echo $pagenav;//输出分页导航

?>
</div>
</body>
</html>


<?php
    $ftpserver=$_POST[ftpserver];
    $ftpport=$_POST[ftpport];
    $ftpuser=$_POST[ftpuser];
    $ftppassword=$_POST[ftppassword];
    $ftp=@ftp_connect($ftpserver,$ftpport);
    if(!$ftp){ echo "连接FTP服务器".$ftpserver."的端口".$ftpport."失败";exit;}
    $rs=@ftp_login($ftp,$ftpuser,$ftppassword);
    if(!$rs){ echo "用户名或密码错误,连接FTP服务器失败";exit;}
    $targetDir=str_replace("\","/",stripslashes($_POST[targetDir]));
    $filename=substr(strrchr($_POST[filelist],"/"),1);
    echo $filename;
//    exit;
    if(substr($targetDir,strlen($targetDir)-1)=="/")
    {
     $rs=@ftp_get($ftp,$targetDir.$filename,$_POST[filelist],FTP_ASCII);
    }else{
     $rs=@ftp_get($ftp,$targetDir."/".$filename,$_POST[filelist],FTP_ASCII);
    }
    if($rs)
    {
     if(substr($targetDir,strlen($targetDir)-1)=="/")
     {
      echo "<script>alert('文件下载成功,文件在本机中路径为[".$targetDir.$filename."]');window.close();</script>";
     }else{
      echo "<script>alert('文件下载成功,文件在本机中路径为[".$targetDir."/".$filename."]');window.close();</script>";
     }
     exit;我是
    }else{
     echo "<script>alert('文件下载失败,请检查目标文件夹是否存在,源文件为[".$_POST[filelist]."]');window.close();</script>";
     exit;
    }
?>
[!--infotagslink--]

相关文章

  • C#连接SQL数据库和查询数据功能的操作技巧

    本文给大家分享C#连接SQL数据库和查询数据功能的操作技巧,本文通过图文并茂的形式给大家介绍的非常详细,需要的朋友参考下吧...2021-05-17
  • php简单数据操作的实例

    最基础的对数据的增加删除修改操作实例,菜鸟们收了吧...2013-09-26
  • 解决Mybatis 大数据量的批量insert问题

    这篇文章主要介绍了解决Mybatis 大数据量的批量insert问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-01-09
  • c#自带缓存使用方法 c#移除清理缓存

    这篇文章主要介绍了c#自带缓存使用方法,包括获取数据缓存、设置数据缓存、移除指定数据缓存等方法,需要的朋友可以参考下...2020-06-25
  • Antd-vue Table组件添加Click事件,实现点击某行数据教程

    这篇文章主要介绍了Antd-vue Table组件添加Click事件,实现点击某行数据教程,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-11-17
  • 详解如何清理redis集群的所有数据

    这篇文章主要介绍了详解如何清理redis集群的所有数据,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-02-18
  • vue 获取到数据但却渲染不到页面上的解决方法

    这篇文章主要介绍了vue 获取到数据但却渲染不到页面上的解决方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-11-19
  • php把读取xml 文档并转换成json数据代码

    在php中解析xml文档用专门的函数domdocument来处理,把json在php中也有相关的处理函数,我们要把数据xml 数据存到一个数据再用json_encode直接换成json数据就OK了。...2016-11-25
  • mybatis-plus 处理大数据插入太慢的解决

    这篇文章主要介绍了mybatis-plus 处理大数据插入太慢的解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-12-18
  • IDEA中的clean,清除项目缓存图文教程

    这篇文章主要介绍了IDEA中的clean,清除项目缓存图文教程,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-09-25
  • postgresql数据添加两个字段联合唯一的操作

    这篇文章主要介绍了postgresql数据添加两个字段联合唯一的操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-02-04
  • Vue生命周期activated之返回上一页不重新请求数据操作

    这篇文章主要介绍了Vue生命周期activated之返回上一页不重新请求数据操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-07-26
  • c# socket网络编程接收发送数据示例代码

    这篇文章主要介绍了c# socket网络编程,server端接收,client端发送数据,大家参考使用吧...2020-06-25
  • 解决vue watch数据的方法被调用了两次的问题

    这篇文章主要介绍了解决vue watch数据的方法被调用了两次的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-11-07
  • vue 数据(data)赋值问题的解决方案

    这篇文章主要介绍了vue 数据(data)赋值问题的解决方案,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-03-29
  • Python3 常用数据标准化方法详解

    这篇文章主要介绍了Python3 常用数据标准化方法详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-03-24
  • iOS蓝牙设备名称缓存问题的解决方法

    这篇文章主要给大家介绍了关于iOS蓝牙设备名称缓存问题的解决方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-12-08
  • node.js从数据库获取数据

    这篇文章主要为大家详细介绍了node.js从数据库获取数据的具体代码,nodejs可以获取具体某张数据表信息,感兴趣的朋友可以参考一下...2016-05-09
  • AngularJS实现Model缓存的方式

    这篇文章主要介绍了AngularJS实现Model缓存的方式,分享了多种AngularJS实现Model缓存的方法,感兴趣的小伙伴们可以参考一下...2016-02-05
  • Nodejs下DNS缓存问题浅析

    本文给大家一起探讨nodejs下dns的缓存问题,本文给大家介绍的非常详细,感兴趣的朋友一起看看吧...2016-11-22