php 数据库mysql查询与连接类
<?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
/**
* cache class
*/
class Cache {
/**
* cache path
*
* @var string
*/
var $cache_path;
/**
* timeout
*
* @var integer
*/
var $time = 60;
/**
* construct for this class
*
* @param string $cache_path
* @return Cache
*/
function Cache($cache_path = 'cache') {
if(is_dir($cache_path)) {
$this->cache_path = rtrim($cache_path,'/').'/';
} else {
die('cache dir is not exists.');
}
}
/**
* set timeout
*
* @param integer $time
* @return boolean
*/
function setTime($time) {
if(isset($time) && is_integer($time)) {
$this->time = $time;
return true;
} else {
return false;
}
}
/**
* read cache
*
* @param string $cache_id
* @return mixed
*/
function read($cache_id) {
$cache_file = $this->cache_path.$cache_id.'.cache';
if(!file_exists($cache_file)) {
return false;
}
$mtime = filemtime($cache_file);
if((time() - $mtime) > $this->time) {
return false;
} else {
$fp = fopen($cache_file,'r');
$content = fread($fp,filesize($cache_file));
fclose($fp);
unset($fp);
if($content) {
return unserialize($content);
} else {
return false;
}
}
}
/**
* write cache in a file
*
* @param string $content
* @param string $cache_id
* @return boolean
*/
function write($content,$cache_id) {
$cache_file = $this->cache_path.$cache_id.'.cache';
if(file_exists($cache_file)) {
@unlink($cache_file);
}
$fp = fopen($cache_file,'w');
$content = serialize($content);
if(fwrite($fp,$content)) {
fclose($fp);
unset($fp);
return true;
} else {
fclose($fp);
unset($fp);
return false;
}
}
/**
* clean all cache
*
* @param string $path
* @return boolean
*/
function cleanCache($path = 'cache') {
if(is_dir($path)) {
$path = rtrim($path,'/').'/';
$handler = opendir($path);
while (($f = readdir($handler)) !== false) {
if(!is_dir($f)) {
if($f != '.' && $f != '..') {
@unlink($path.$f);
}
} else {
$this->cleanCache($f);
}
}
} else {
return false;
}
}
}
?>
/**
* 作者:初十
* 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
$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;'>>>>{$data}</div>");
}
}
function get()
{
if ($data = @fgets($this->connect, $this->maxMessage))
{
if ($this->debug)
print("<div style='color:red;font-size:13px;'><<<{$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>
相关文章
- 操作类就是把一些常用的一系列的数据库或相关操作写在一个类中,这样调用时我们只要调用类文件,如果要执行相关操作就直接调用类文件中的方法函数就可以实现了,下面整理了...2016-11-25
- 本文给大家分享C#连接SQL数据库和查询数据功能的操作技巧,本文通过图文并茂的形式给大家介绍的非常详细,需要的朋友参考下吧...2021-05-17
- 这篇文章主要介绍了Mybatis Plus select 实现只查询部分字段的操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-09-01
- 最基础的对数据的增加删除修改操作实例,菜鸟们收了吧...2013-09-26
- 这篇文章主要介绍了C#从数据库读取图片并保存的方法,帮助大家更好的理解和使用c#,感兴趣的朋友可以了解下...2021-01-16
- 这篇文章主要介绍了解决Mybatis 大数据量的批量insert问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-01-09
Antd-vue Table组件添加Click事件,实现点击某行数据教程
这篇文章主要介绍了Antd-vue Table组件添加Click事件,实现点击某行数据教程,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-11-17- 这篇文章主要介绍了详解如何清理redis集群的所有数据,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-02-18
- 这篇文章主要介绍了Intellij IDEA连接Navicat数据库的方法,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借价值,需要的朋友可以参考下...2021-03-25
- 在开发过程中,我们经常会将日期时间的毫秒数存放到数据库,但是它对应的时间看起来就十分不方便,我们可以使用一些函数将毫秒转换成date格式。 一、 在MySQL中,有内置的函数from_unixtime()来做相应的转换,使用如下: 复制...2014-05-31
- 这篇文章主要介绍了vue 获取到数据但却渲染不到页面上的解决方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-11-19
- C#使用System.IO中的文件操作方法在Windows系统中处理本地文件相当顺手,这里我们还总结了在Oracle中保存文件的方法,嗯,接下来就来看看整理的C#操作本地文件及保存文件到数据库的基本方法总结...2020-06-25
- 通过内网连另外一台机器的mysql服务, 确发现速度N慢! 等了大约几十秒才等到提示输入密码。 但是ping mysql所在服务器却很快! 想到很久之前有过类似的经验, telnet等一些服务在连接请求的时候,会做一些反向域名解析(如果...2015-10-21
- 某些时候,例如为了搭建一个测试环境,或者克隆一个网站,需要复制一个已存在的mysql数据库。使用以下方法,可以非常简单地实现。假设已经存在的数据库名字叫db1,想要复制一份,命名为newdb。步骤如下:1. 首先创建新的数据库newd...2015-10-21
- 在php中解析xml文档用专门的函数domdocument来处理,把json在php中也有相关的处理函数,我们要把数据xml 数据存到一个数据再用json_encode直接换成json数据就OK了。...2016-11-25
- 这篇文章主要介绍了mybatis-plus 处理大数据插入太慢的解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-12-18
MyBatisPlus-QueryWrapper多条件查询及修改方式
这篇文章主要介绍了MyBatisPlus-QueryWrapper多条件查询及修改方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2022-06-27- mysqldump命令的用法1、导出所有库系统命令行mysqldump -uusername -ppassword --all-databases > all.sql 2、导入所有库mysql命令行mysql>source all.sql; 3、导出某些库系统命令行mysqldump -uusername -ppassword...2015-10-21
- 这篇文章主要介绍了node.js如何操作MySQL数据库,帮助大家更好的进行web开发,感兴趣的朋友可以了解下...2020-10-29
- 1005:创建表失败1006:创建数据库失败1007:数据库已存在,创建数据库失败1008:数据库不存在,删除数据库失败1009:不能删除数据库文件导致删除数据库失败1010:不能删除数据目录导致删除数据库失败1011:删除数据库...2013-09-23