PHP的PDO常用类库实例分析
本文实例讲述了PHP的PDO常用类库。分享给大家供大家参考,具体如下:
1、Db.class.php连接数据库
<?php
//连接数据库
classDb{
staticpublicfunctiongetDB(){
try{
$pdo=newPDO(DB_DSN,DB_USER,DB_PWD);
$pdo->setAttribute(PDO::ATTR_PERSISTENT,true);//设置数据库连接为持久连接
$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);//设置抛出错误
$pdo->setAttribute(PDO::ATTR_ORACLE_NULLS,true);//设置当字符串为空转换为SQL的NULL
$pdo->query('SETNAMESutf8');//设置数据库编码
}catch(PDOException$e){
exit('数据库连接错误,错误信息:'.$e->getMessage());
}
return$pdo;
}
}
?>
2、Model.class.php数据库操作类
<?php
/**
*数据库操作类库
*authorLee.
*Lastmodify$Date:2012-1-1913:59;04$
*/
classM{
private$_db;//数据库句柄
public$_sql;//SQL语句
/**
*构造方法
*/
publicfunction__construct(){
$this->_db=Db::getDB();
}
/**
*数据库添加操作
*@paramstring$tName表名
*@paramarray$field字段数组
*@paramarray$val值数组
*@parambool$is_lastInsertId是否返回添加ID
*@returnint默认返回成功与否,$is_lastInsertId为true,返回添加ID
*/
publicfunctioninsert($tName,$fields,$vals,$is_lastInsertId=FALSE){
try{
if(!is_array($fields)||!is_array($vals))
exit($this->getError(__FUNCTION__,__LINE__));
$fields=$this->formatArr($fields);
$vals=$this->formatArr($vals,false);
$tName=$this->formatTabName($tName);
$this->_sql="INSERTINTO{$tName}({$fields})VALUES({$vals})";
if(!$is_lastInsertId){
$row=$this->_db->exec($this->_sql);
return$row;
}else{
$this->_db->exec($this->_sql);
$lastId=(int)$this->_db->lastInsertId();
return$lastId;
}
}catch(PDOException$e){
exit($e->getMessage());
}
}
/**
*数据库修改操作
*@paramstring$tName表名
*@paramarray$field字段数组
*@paramarray$val值数组
*@paramstring$condition条件
*@returnint受影响的行数
*/
publicfunctionupdate($tName,$fieldVal,$condition){
try{
if(!is_array($fieldVal)||!is_string($tName)||!is_string($condition))
exit($this->getError(__FUNCTION__,__LINE__));
$tName=$this->formatTabName($tName);
$upStr='';
foreach($fieldValas$k=>$v){
$upStr.='`'.$k.'`='.'\''.$v.'\''.',';
}
$upStr=rtrim($upStr,',');
$this->_sql="UPDATE{$tName}SET{$upStr}WHERE{$condition}";
$row=$this->_db->exec($this->_sql);
return$row;
}catch(PDOException$e){
exit($e->getMessage());
}
}
/**
*数据库删除操作(注:必须添加where条件)
*@paramstring$tName表名
*@paramstring$condition条件
*@returnint受影响的行数
*/
publicfunctiondel($tName,$condition){
try{
if(!is_string($tName)||!is_string($condition))
exit($this->getError(__FUNCTION__,__LINE__));
$tName=$this->formatTabName($tName);
$this->_sql="DELETEFROM{$tName}WHERE{$condition}";
$row=$this->_db->exec($this->_sql);
return$row;
}catch(PDOException$e){
exit($e->getMessage());
}
}
/**
*返回表总个数
*@paramstring$tName表名
*@paramstring$condition条件
*@returnint
*/
publicfunctiontotal($tName,$condition=''){
try{
if(!is_string($tName))
exit($this->getError(__FUNCTION__,__LINE__));
$tName=$this->formatTabName($tName);
$this->_sql="SELECTCOUNT(*)AStotalFROM{$tName}".
($condition==''?'':'WHERE'.$condition);
$re=$this->_db->query($this->_sql);
foreach($reas$v){
$total=$v['total'];
}
return(int)$total;
}catch(PDOException$e){
exit($e->getMessage());
}
}
/**
*数据库删除多条数据
*@paramstring$tName表名
*@paramstring$field依赖字段
*@paramarray$ids删除数组
*@returnint受影响的行数
*/
publicfunctiondelMulti($tName,$field,$ids){
try{
if(!is_string($tName)||!is_array($ids))
exit($this->getError(__FUNCTION__,__LINE__));
$delStr='';
$tName=$this->formatTabName($tName);
$field=$this->formatTabName($field);
foreach($idsas$v){
$delStr.=$v.',';
}
$delStr=rtrim($delStr,',');
$this->_sql="DELETEFROM{$tName}WHERE{$field}IN({$delStr})";
$row=$this->_db->exec($this->_sql);
return$row;
}catch(PDOException$e){
exit($e->getMessage());
}
}
/**
*获取表格的最后主键(注:针对INT类型)
*@paramstring$tName表名
*@returnint
*/
publicfunctioninsertId($tName){
try{
if(!is_string($tName))
exit($this->getError(__FUNCTION__,__LINE__));
$this->_sql="SHOWTABLESTATUSLIKE'{$tName}'";
$result=$this->_db->query($this->_sql);
$insert_id=0;
foreach($resultas$v){
$insert_id=$v['Auto_increment'];
}
return(int)$insert_id;
}catch(PDOException$e){
exit($e->getMessage());
}
}
/**
*检查数据是否已经存在(依赖条件)
*@paramstring$tName表名
*@paramstring$field依赖的字段
*@returnbool
*/
publicfunctionexists($tName,$condition){
try{
if(!is_string($tName)||!is_string($condition))
exit($this->getError(__FUNCTION__,__LINE__));
$tName=$this->formatTabName($tName);
$this->_sql="SELECTCOUNT(*)AStotalFROM{$tName}WHERE{$condition}";
$result=$this->_db->query($this->_sql);
foreach($resultas$v){
$b=$v['total'];
}
if($b){
returntrue;
}else{
returnfalse;
}
}catch(PDOException$e){
exit($e->getMessage());
}
}
/**
*检查数据是否已经存在(依赖INT主键)
*@paramstring$tName表名
*@paramstring$primary主键
*@paramint$id主键值
*@returnbool
*/
publicfunctionexistsByPK($tName,$primary,$id){
try{
if(!is_string($tName)||!is_string($primary)
||!is_int($id))
exit($this->getError(__FUNCTION__,__LINE__));
$tName=$this->formatTabName($tName);
$this->_sql="SELECTCOUNT(*)AStotalFROM{$tName}WHERE{$primary}=".$id;
$result=$this->_db->query($this->_sql);
foreach($resultas$v){
$b=$v['total'];
}
if($b){
returntrue;
}else{
returnfalse;
}
}catch(PDOException$e){
exit($e->getMessage());
}
}
/**
*预处理删除(注:针对主键为INT类型,推荐使用)
*@paramstring$tName表名
*@paramstring$primary主键字段
*@paramintorarrayorstring$ids如果是删除一条为INT,多条为array,删除一个范围为string
*@returnint返回受影响的行数
*/
publicfunctiondelByPK($tName,$primary,$ids,$mult=FALSE){
try{
if(!is_string($tName)||!is_string($primary)
||(!is_int($ids)&&!is_array($ids)&&!is_string($ids))
||!is_bool($mult))exit($this->getError(__FUNCTION__,__LINE__));
$tName=$this->formatTabName($tName);
$stmt=$this->_db->prepare("DELETEFROM{$tName}WHERE{$primary}=?");
if(!$mult){
$stmt->bindParam(1,$ids);
$row=$stmt->execute();
}else{
if(is_array($ids)){
$row=0;
foreach($idsas$v){
$stmt->bindParam(1,$v);
if($stmt->execute()){
$row++;
}
}
}elseif(is_string($ids)){
if(!strpos($ids,'-'))
exit($this->getError(__FUNCTION__,__LINE__));
$split=explode('-',$ids);
if(count($split)!=2||$split[0]>$split[1])
exit($this->getError(__FUNCTION__,__LINE__));
$i=null;
$count=$split[1]-$split[0]+1;
for($i=0;$i<$count;$i++){
$idArr[$i]=$split[0]++;
}
$idStr='';
foreach($idArras$id){
$idStr.=$id.',';
}
$idStr=rtrim($idStr,',');
$this->_sql="DELETEFROM{$tName}WHERE{$primary}in({$idStr})";
$row=$this->_db->exec($this->_sql);
}
}
return$row;
}catch(PDOException$e){
exit($e->getMessage());
}
}
/**
*返回单个字段数据或单条记录
*@paramstring$tName表名
*@paramstring$condition条件
*@paramstringorarray$fields返回的字段,默认是*
*@returnstring||array
*/
publicfunctiongetRow($tName,$condition='',$fields="*"){
try{
if(!is_string($tName)||!is_string($condition)
||!is_string($fields)||empty($fields))
exit($this->getError(__FUNCTION__,__LINE__));
$tName=$this->formatTabName($tName);
$this->_sql="SELECT{$fields}FROM{$tName}";
$this->_sql.=($condition==''?'':"WHERE{$condition}")."LIMIT1";
$sth=$this->_db->prepare($this->_sql);
$sth->execute();
$result=$sth->fetch(PDO::FETCH_ASSOC);
if($fields==='*'){
return$result;
}else{
return$result[$fields];
}
}catch(PDOException$e){
exit($e->getMessage());
}
}
/**
*返回多条数据
*@paramstring$tName表名
*@paramstring$fields返回字段,默认为*
*@paramstring$condition条件
*@paramstring$order排序
*@paramstring$limit显示个数
*@returnPDOStatement
*/
publicfunctiongetAll($tName,$fields='*',$condition='',$order='',$limit=''){
try{
if(!is_string($tName)||!is_string($fields)
||!is_string($condition)||!is_string($order)
||!is_string($limit))
exit($this->getError(__FUNCTION__,__LINE__));
$tName=$this->formatTabName($tName);
$fields=($fields=='*'||$fields=='')?'*':$fields;
$condition=$condition==''?'':"WHERE".$condition;
$order=$order==''?'':"ORDERBY".$order;
$limit=$limit==''?'':"LIMIT".$limit;
$this->_sql="SELECT{$fields}FROM{$tName}{$condition}{$order}{$limit}";
$sth=$this->_db->prepare($this->_sql);
$sth->execute();
$result=$sth->fetchAll(PDO::FETCH_ASSOC);
return$result;
}catch(PDOException$e){
exit($e->getMessage());
}
}
/**
*格式化数组(表结构和值)
*@paramarray$field
*@parambool$isField
*@returnstring
*/
privatefunctionformatArr($field,$isField=TRUE){
if(!is_array($field))exit($this->getError(__FUNCTION__,__LINE__));
$fields='';
if($isField){
foreach($fieldas$v){
$fields.='`'.$v.'`,';
}
}else{
foreach($fieldas$v){
$fields.='\''.$v.'\''.',';
}
}
$fields=rtrim($fields,',');
return$fields;
}
/**
*格式化问号
*@paramint$count数量
*@returnstring返回格式化后的字符串
*/
privatefunctionformatMark($count){
$str='';
if(!is_int($count))exit($this->getError(__FUNCTION__,__LINE__));
if($count==1)return'?';
for($i=0;$i<$count;$i++){
$str.='?,';
}
returnrtrim($str,',');
}
/**
*错误提示
*@paramstring$fun
*@returnstring
*/
privatefunctiongetError($fun,$line){
return__CLASS__.'->'.$fun.'()line<fontcolor="red">'.$line.'</font>ERROR!';
}
/**
*处理表名
*@paramstring$tName
*@returnstring
*/
privatefunctionformatTabName($tName){
return'`'.trim($tName,'`').'`';
}
/**
*析构方法
*/
publicfunction__destruct(){
$this->_db=null;
}
}
更多关于PHP相关内容感兴趣的读者可查看本站专题:《phpcurl用法总结》、《PHP运算与运算符用法总结》、《PHP网络编程技巧总结》、《PHP基本语法入门教程》、《php操作office文档技巧总结(包括word,excel,access,ppt)》、《php日期与时间用法总结》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家PHP程序设计有所帮助。