本文介绍一个基于PHP PDO封装的MySQL数据库操作类。针对原生PDO操作中SQL语句拼接繁琐、易出错的问题,该封装类提供了统一的select、insert、update和delete接口,支持将查询条件或更新字段以数组形式传入,自动完成语法组装。同时,类结构支持多实例化,方便在同一项目中处理多个数据库连接的交互场景。
解决的核心问题
在直接使用PDO进行开发时,开发者常面临以下痛点:
- SQL拼接复杂:尤其是INSERT语句,字段名(fields)与值(values)需要严格一一对应,手动维护顺序极易出现偏差。
- WHERE条件拼装成本高:随着查询条件增多,手动拼接字符串不仅代码冗长,还容易遗漏"AND"关键字或引号转义问题。
- 多库连接管理困难:若需连接不同数据库,通常需复制大量重复的连接配置代码,难以复用。
为了解决上述问题,本示例提供一个简化的HRDB类。虽然它不包含复杂的ORM映射功能,但通过封装基础CRUD操作和参数预处理,能显著提升日常简单数据操作的效率和安全性。
关键特性说明
第1步:利用SET语法简化Insert插入
传统MySQL INSERT语句要求明确指定列名和对应的值列表。本类采用MySQL特有的 INSERT INTO table SET col=value 语法。这种写法类似UPDATE语句,直观且无需担心列与值的顺序对应问题,尤其适合动态生成插入内容的场景。
复制代码 代码如下:
insert into tb_member set username = "test", type = 1, lastlogindt = now()
在类的实现中,$set 参数可以直接接受一个数组,内部会自动使用逗号将其拼接为上述格式,极大减少了前端构造SQL的工作量。
第2步:数组模式拼装WHERE与SET条件
对于复杂的查询(SELECT/DELETE)或更新(UPDATE),往往涉及多个条件。原类允许 $sqlwhere 和 $set 参数接收字符串或数组。当传入数组时,类会自动处理逻辑连接符(如 ' and '),避免开发者手动处理逻辑判断和符号添加。
例如,删除数据的调用方式:
复制代码 代码如下:
$where = array(
'tbid = 1',
'username = "hooray"'
);
$db->delete(1, 0, 'tb_member', $where);
同样,更新操作中的 $set 也可以这样传递,保持代码清晰:
复制代码 代码如下:
$set = array('username = "123"', 'type = 1', 'lastlogindt = now()');
$where = array('tbid = 1');
$db->update(1, 0, 'tb_member', $set, $where);
第3步:内置调试模式辅助排错
在开发阶段,直接查看生成的最终SQL语句有助于排查逻辑错误。该类在各个操作方法中都加入了 $debug 参数控制:
0:正常执行,静默运行。
1:仅在前端echo出即将执行的SQL语句,不终止程序。
2:输出SQL语句后直接 exit 终止页面,防止意外操作数据库。
这使得在遇到“查询结果为空”或“数据未更新”时,能快速定位是参数传错还是SQL语法有误。
第4步:支持多数据库连接实例
不同于某些单例模式的通用类,此HRDB类的设计允许灵活的多实例创建。只需构造不同的配置文件数组(包含dsn、账号、密码),即可实例化多个对象,分别指向不同的数据库服务器或库。
复制代码 代码如下:
$db_hoorayos_config = array(
'dsn'=>'mysql:host=localhost;dbname=hoorayos',
'name'=>'root',
'password'=>'hooray'
);
$db = new HRDB($db_hoorayos_config);
$db_hoorayos_config2 = array(
'dsn'=>'mysql:host=localhost;dbname=hoorayos2',
'name'=>'root',
'password'=>'hooray'
);
$db2 = new HRDB($db_hoorayos_config2);
完整代码参考
以下是该数据库操作类的完整源代码,包含了连接管理、事务隔离级别的设置以及各方法的详细注释。请注意,生产环境中建议结合预处理语句(Prepared Statements)来彻底杜绝SQL注入风险,当前版本侧重于操作便捷性演示。
复制代码 代码如下:
/**
* 作者:胡睿
* 日期:2012/07/21
*/
class HRDB{
protected $pdo;
protected $res;
protected $config;
/*构造函数*/
function __construct($config){
$this->Config = $config;
$this->connect();
}
/*数据库连接*/
public function connect(){
$this->pdo = new PDO($this->Config['dsn'], $this->Config['name'], $this->Config['password']);
$this->pdo->query('set names utf8;');
//$this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
//开启异常模式以便捕获错误
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
/*数据库关闭*/
public function close(){
$this->pdo = null;
}
public function query($sql){
$res = $this->pdo->query($sql);
if($res){
$this->res = $res;
}
}
public function exec($sql){
$res = $this->pdo->exec($sql);
if($res){
$this->res = $res;
}
}
public function fetchAll(){
return $this->res->fetchAll();
}
public function fetch(){
return $this->res->fetch();
}
public function fetchColumn(){
return $this->res->fetchColumn();
}
public function lastInsertId(){
return $this->res->lastInsertId();
}
/**
* SELECT查询
* int $debug 调试级别 (0:无输出, 1:输出SQL, 2:输出并退出)
* int $mode 返回类型 (0:全表, 1:单条, 2:计数)
* string/array $table 表名
* string/array $fields 字段
* string/array $sqlwhere 条件
* string $orderby 排序
*/
public function select($debug, $mode, $table, $fields="*", $sqlwhere="", $orderby="tbid desc"){
if(is_array($table)) { $table = implode(', ', $table); }
if(is_array($fields)) { $fields = implode(', ', $fields); }
if(is_array($sqlwhere)) { $sqlwhere = ' and '.implode(' and ', $sqlwhere); }
if($debug === 0){
if($mode === 2) {
$this->query("select count(tbid) from $table where 1=1 $sqlwhere");
$return = $this->fetchColumn();
} else if($mode === 1) {
$this->query("select $fields from $table where 1=1 $sqlwhere order by $orderby");
$return = $this->fetch();
} else {
$this->query("select $fields from $table where 1=1 $sqlwhere order by $orderby");
$return = $this->fetchAll();
}
return $return;
} else {
$sql = ($mode===2)? "select count(tbid) from $table where 1=1 $sqlwhere"
: "select $fields from $table where 1=1 $sqlwhere order by $orderby";
echo $sql;
if($debug === 2) exit;
}
}
/**
* INSERT插入
* int $mode 返回类型 (0:无返回, 1:受行数, 2:新ID)
* string/array $table 表名
* string/array $set 字段设置 ('col=val')
*/
public function insert($debug, $mode, $table, $set){
if(is_array($table)) { $table = implode(', ', $table); }
if(is_array($set)) { $set = implode(', ', $set); }
if($debug === 0){
if($mode === 2) {
$this->query("insert into $table set $set");
$return = $this->lastInsertId();
} else if($mode === 1) {
$this->exec("insert into $table set $set");
$return = $this->res;
} else {
$this->query("insert into $table set $set");
$return = NULL;
}
return $return;
} else {
echo "insert into $table set $set";
if($debug === 2) exit;
}
}
/**
* UPDATE更新
*/
public function update($debug, $mode, $table, $set, $sqlwhere=""){
if(is_array($table)) { $table = implode(', ', $table); }
if(is_array($set)) { $set = implode(', ', $set); }
if(is_array($sqlwhere)) { $sqlwhere = ' and '.implode(' and ', $sqlwhere); }
if($debug === 0){
if($mode === 1) {
$this->exec("update $table set $set where 1=1 $sqlwhere");
$return = $this->res;
} else {
$this->query("update $table set $set where 1=1 $sqlwhere");
$return = NULL;
}
return $return;
} else {
echo "update $table set $set where 1=1 $sqlwhere";
if($debug === 2) exit;
}
}
/**
* DELETE删除
*/
public function delete($debug, $mode, $table, $sqlwhere=""){
if(is_array($sqlwhere)) { $sqlwhere = ' and '.implode(' and ', $sqlwhere); }
if($debug === 0){
if($mode === 1) {
$this->exec("delete from $table where 1=1 $sqlwhere");
$return = $this->res;
} else {
$this->query("delete from $table where 1=1 $sqlwhere");
$return = NULL;
}
return $return;
} else {
echo "delete from $table where 1=1 $sqlwhere";
if($debug === 2) exit;
}
}
}
测试用例参考
在实际使用中,可以通过简单的脚本验证各个功能模块。以下是一个集成测试片段,展示了如何使用字符串模式和数组模式进行操作。
复制代码 代码如下:
require_once('global.php');
require_once('inc/setting.inc.php');
$db = new HRDB($db_hoorayos_config);
echo '
select测试
';
$rs = $db->select(1, 0, 'tb_member', 'username, password', 'and type = 1 and username like "%os%"');
$fields = array('username', 'password');
$where = array('type = 1', 'username like "%os%"');
$rs = $db->select(1, 0, 'tb_member', $fields, $where);
echo '
insert测试
';
$db->insert(1, 0, 'tb_member', 'username = "test", type = 1');
$set = array('username = "test"', 'type = 1');
$db->insert(1, 0, 'tb_member', $set);
echo '
update测试
';
$db->update(1, 0, 'tb_member', 'username = "123"', 'and tbid = 7');
$set = array('username = "123"');
$where = array('tbid = 1');
$db->update(1, 0, 'tb_member', $set, $where);
echo '
delete测试
';
$db->delete(1, 0, 'tb_member', 'and tbid = 1');
echo '
自定义sql
';
$db->query('select * from tb_member limit 1');
var_dump($db->fetchAll());
$db->close();
以上就是基于PHP PDO封装MySQL数据库操作类的详细内容,更多关于PHP高级应用及数据库优化的资料请关注本站其它相关文章!