基于PDO的通用数据库操作类实现
经过调研后决定采用PDO作为数据库连接方式,其具体优势此处不再赘述,读者可自行查阅相关资料了解。
既然决定更换驱动,首要任务便是构建一个基础的数据库操作类,以实现常见的增删改查等功能。经过一晚的开发,初步完成了该类的设计,以下展示相关代码,期待各位提出改进建议。
具体实现代码如下:
<?php
/*
作者:胡睿
日期:2011/03/19
电邮:hooray0905@foxmail.com
20110319
该类提供常用的数据库操作,包括增删改查、获取单条或多条记录、返回最新插入记录的ID以及操作影响的行数等。
*/
/*
参数说明
int $debug 是否开启调试模式,若开启则直接输出生成的SQL语句。
int $getcount 是否统计行数,返回值即为受影响的行数。
int $getrow 是否仅返回单条记录结果。
string $table 指定操作的数据库表名。
string $fields 指定需要查询的字段,允许为空,默认为查询所有字段。
string $sqlwhere 指定查询条件,允许为空。
string $orderby 指定排序规则,允许为空,默认为按id倒序排列。
*/
function hrSelect($debug, $getcount, $getrow, $table, $fields="*", $sqlwhere="", $orderby="id desc"){
global $pdo;
if($debug){
if($getcount){
echo "select count(*) from $table where 1=1 $sqlwhere order by $orderby";
}else{
echo "select $fields from $table where 1=1 $sqlwhere order by $orderby";
}
exit;
}else{
if($getcount){
$rs = $pdo->query("select count(*) from $table where 1=1 $sqlwhere order by $orderby");
return $rs->fetchColumn();
}elseif($getrow){
$rs = $pdo->query("select $fields from $table where 1=1 $sqlwhere order by $orderby");
return $rs->fetch();
}else{
$rs = $pdo->query("select $fields from $table where 1=1 $sqlwhere order by $orderby");
return $rs->fetchAll();
}
}
}
/*
参数说明
int $debug 是否开启调试模式,若开启则直接输出生成的SQL语句。
int $execrow 是否开启返回执行条目数的功能。
int $lastinsertid 是否开启返回最后一条插入记录ID的功能。
string $table 指定操作的数据库表名。
string $fields 指定需要插入数据库的字段列表。
string $values 指定需要插入的数据值,必须与$fields一一对应。
*/
function hrInsert($debug, $execrow, $lastinsertid, $table, $fields, $values){
global $pdo;
if($debug){
echo "insert into $table ($fields) values ($values)";
exit;
}elseif($execrow){
return $pdo->exec("insert into $table ($fields) values ($values)");
}elseif($lastinsertid){
return $pdo->lastInsertId("insert into $table ($fields) values ($values)");
}else{
$pdo->query("insert into $table ($fields) values ($values)");
}
}
/*
参数说明
int $debug 是否开启调试模式,若开启则直接输出生成的SQL语句。
int $execrow 是否开启执行并返回受影响条目数的功能。
string $table 指定操作的数据库表名。
string $set 指定需要更新的字段及内容,格式示例:a='abc',b=2,c='2010-10-10 10:10:10'。
string $sqlwhere 指定修改条件,允许为空。
*/
function hrUpdate($debug, $execrow, $table, $set, $sqlwhere=""){
global $pdo;
if($debug){
echo "update $table set $set where 1=1 $sqlwhere";
exit;
}elseif($execrow){
return $pdo->exec("update $table set $set where 1=1 $sqlwhere");
}else{
$pdo->query("update $table set $set where 1=1 $sqlwhere");
}
}
/*
参数说明
int $debug 是否开启调试模式,若开启则直接输出生成的SQL语句。
int $execrow 是否开启返回执行条目数的功能。
string $table 指定操作的数据库表名。
string $sqlwhere 指定删除条件,允许为空。
*/
function hrDelete($debug, $execrow, $table, $sqlwhere=""){
global $pdo;
if($debug){
echo "delete from $table where 1=1 $sqlwhere";
exit;
}elseif($execrow){
return $pdo->exec("delete from $table where 1=1 $sqlwhere");
}else{
$pdo->query("delete from $table where 1=1 $sqlwhere");
}
}
?> 参数的注释都写的很清楚,如果有人需要,不清楚使用方法可以直接问我。