PHP用PDO如何封装简单易用的DB类详解
作者:火蜥蜴 时间:2023-11-23 16:05:39
前言
PDO扩展为PHP访问数据库定义了一个轻量级的、一致性的接口,它提供了一个数据访问抽象层,这样,无论使用什么数据库,都可以通过一致的函数执行查询和获取数据。PDO随PHP5.1发行,在PHP5.0的PECL扩展中也可以使用。
我个人理解:PDO是一个抽象类,为我们提供访问数据的接口方法,下面这篇将给大家介绍关于PHP如何利用PDO封装简单易用的DB类,下面话不多说,来一起看看详细的介绍:
使用
创建测试库和表
create database db_test;
CREATE TABLE `user` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` char(11) NOT NULL,
`created_at` int(10) unsigned NOT NULL,
PRIMARY KEY (`uid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `user` VALUES ('1', 'wang', '1501109027');
INSERT INTO `user` VALUES ('2', 'meng', '1501109026');
INSERT INTO `user` VALUES ('3', 'liu', '1501009027');
INSERT INTO `user` VALUES ('4', 'yuan', '1500109027');
代码测试
require __DIR__ . '/DB.php';
$db = new DB();
$db->__setup([
'dsn'=>'mysql:dbname=db_test;host=localhost',
'username'=>'root',
'password'=>'******',
'charset'=>'utf8'
]);
$user = $db->fetch('SELECT * FROM user where id = :id', ['id' => 1]);
echo $user['name'];
echo "\n";
$insertId = $db->insert('user', ['name' => 'salamander', 'created_at' => time()]);
echo "insert user {$insertId}\n";
$users = $db->fetchAll('SELECT * FROM user');
foreach ($users as $item) {
echo "user {$item['id']} is {$item['name']} \n";
}
运行结果
DB工具类
<?php
/**
* User: Salamander
* Date: 2016/9/2
* Time: 9:16
*/
class DB
{
private $dsn;
private $sth;
private $dbh;
private $user;
private $charset;
private $password;
public $lastSQL = '';
public function __setup($config = array())
{
$this->dsn = $config['dsn'];
$this->user = $config['username'];
$this->password = $config['password'];
$this->charset = $config['charset'];
$this->connect();
}
private function connect()
{
if(!$this->dbh){
$options = array(
\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES ' . $this->charset,
);
$this->dbh = new \PDO($this->dsn, $this->user,
$this->password, $options);
}
}
public function beginTransaction()
{
return $this->dbh->beginTransaction();
}
public function inTransaction()
{
return $this->dbh->inTransaction();
}
public function rollBack()
{
return $this->dbh->rollBack();
}
public function commit()
{
return $this->dbh->commit();
}
function watchException($execute_state)
{
if(!$execute_state){
throw new MySQLException("SQL: {$this->lastSQL}\n".$this->sth->errorInfo()[2], intval($this->sth->errorCode()));
}
}
public function fetchAll($sql, $parameters=[])
{
$result = [];
$this->lastSQL = $sql;
$this->sth = $this->dbh->prepare($sql);
$this->watchException($this->sth->execute($parameters));
while($result[] = $this->sth->fetch(\PDO::FETCH_ASSOC)){ }
array_pop($result);
return $result;
}
public function fetchColumnAll($sql, $parameters=[], $position=0)
{
$result = [];
$this->lastSQL = $sql;
$this->sth = $this->dbh->prepare($sql);
$this->watchException($this->sth->execute($parameters));
while($result[] = $this->sth->fetch(\PDO::FETCH_COLUMN, $position)){ }
array_pop($result);
return $result;
}
public function exists($sql, $parameters=[])
{
$this->lastSQL = $sql;
$data = $this->fetch($sql, $parameters);
return !empty($data);
}
public function query($sql, $parameters=[])
{
$this->lastSQL = $sql;
$this->sth = $this->dbh->prepare($sql);
$this->watchException($this->sth->execute($parameters));
return $this->sth->rowCount();
}
public function fetch($sql, $parameters=[], $type=\PDO::FETCH_ASSOC)
{
$this->lastSQL = $sql;
$this->sth = $this->dbh->prepare($sql);
$this->watchException($this->sth->execute($parameters));
return $this->sth->fetch($type);
}
public function fetchColumn($sql, $parameters=[], $position=0)
{
$this->lastSQL = $sql;
$this->sth = $this->dbh->prepare($sql);
$this->watchException($this->sth->execute($parameters));
return $this->sth->fetch(\PDO::FETCH_COLUMN, $position);
}
public function update($table, $parameters=[], $condition=[])
{
$table = $this->format_table_name($table);
$sql = "UPDATE $table SET ";
$fields = [];
$pdo_parameters = [];
foreach ( $parameters as $field=>$value){
$fields[] = '`'.$field.'`=:field_'.$field;
$pdo_parameters['field_'.$field] = $value;
}
$sql .= implode(',', $fields);
$fields = [];
$where = '';
if(is_string($condition)) {
$where = $condition;
} else if(is_array($condition)) {
foreach($condition as $field=>$value){
$parameters[$field] = $value;
$fields[] = '`'.$field.'`=:condition_'.$field;
$pdo_parameters['condition_'.$field] = $value;
}
$where = implode(' AND ', $fields);
}
if(!empty($where)) {
$sql .= ' WHERE '.$where;
}
return $this->query($sql, $pdo_parameters);
}
public function insert($table, $parameters=[])
{
$table = $this->format_table_name($table);
$sql = "INSERT INTO $table";
$fields = [];
$placeholder = [];
foreach ( $parameters as $field=>$value){
$placeholder[] = ':'.$field;
$fields[] = '`'.$field.'`';
}
$sql .= '('.implode(",", $fields).') VALUES ('.implode(",", $placeholder).')';
$this->lastSQL = $sql;
$this->sth = $this->dbh->prepare($sql);
$this->watchException($this->sth->execute($parameters));
$id = $this->dbh->lastInsertId();
if(empty($id)) {
return $this->sth->rowCount();
} else {
return $id;
}
}
public function errorInfo()
{
return $this->sth->errorInfo();
}
protected function format_table_name($table)
{
$parts = explode(".", $table, 2);
if(count($parts) > 1) {
$table = $parts[0].".`{$parts[1]}`";
} else {
$table = "`$table`";
}
return $table;
}
function errorCode()
{
return $this->sth->errorCode();
}
}
class MySQLException extends \Exception { }
框架中使用建议
在框架中使用DB类,用单例模式或者用依赖容器来管理较好。
来源:https://segmentfault.com/a/1190000010391179
标签:php,pdo,封装db类
0
投稿
猜你喜欢
JS重载实现方法分析
2023-10-07 08:09:04
Zend Studio去除编辑器的语法警告设置方法
2023-10-11 17:10:15
django中模板的html自动转意方法
2023-06-28 15:33:49
python实现对excel进行数据剔除操作实例
2022-09-28 13:53:22
Python中Yield的基本用法
2021-08-30 15:34:55
Jquery对数组的操作技巧整理
2024-04-22 22:32:52
详解Pycharm与anaconda安装配置指南
2022-09-24 01:51:45
CentOS 7下Python 2.7升级至Python3.6.1的实战教程
2023-09-13 07:56:46
Windows下将Python文件打包成.EXE可执行文件的方法
2021-08-04 02:47:59
ASP:使用ImageMagickObject组件制作缩略图
2008-10-21 12:21:00
关注各网站的布局调整
2008-09-23 18:14:00
关于Mysql5.7及8.0版本索引失效情况汇总
2024-01-21 08:35:35
加载 Javascript 最佳实践
2011-01-16 18:29:00
Go 语言结构实例分析
2024-04-23 09:46:36
Python实现的特征提取操作示例
2023-02-07 06:08:04
解决Pycharm出现的部分快捷键无效问题
2021-09-12 12:49:34
下拉列表两级连动的新方法(二)
2009-06-04 18:22:00
php使用composer常见问题及解决办法
2023-07-10 13:54:53
随滚动条移动的DIV层js代码
2007-10-10 12:51:00
详解JavaScript中的Object.is()与"==="运算符总结
2024-04-22 12:50:25