🗣 Wd提问: PHP二次开发PDO
🤖 Ai回答: PHP PDO 二次开发指南
PDO (PHP Data Objects) 是 PHP 中访问数据库的轻量级接口,为不同的数据库系统提供统一的访问方式。以下是 PDO 的二次开发指南:
1、PDO 基础封装
php
class Database {
private $pdo;
private $error;
public function __construct($host, $dbname, $user, $pass, $charset = 'utf8') {
$dsn = mysql:host=$host;dbname=$dbname;charset=$charset;
$options = [
PDO::ATTR_ERRMODE = PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE = PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES = false,
];
try {
$this-pdo = new PDO($dsn, $user, $pass, $options);
} catch (PDOException $e) {
$this-error = $e-getMessage();
throw new Exception(数据库连接失败: 、$this-error);
}
}
public function getConnection() {
return $this-pdo;
}
}
2、查询构建器扩展
php
class QueryBuilder {
protected $pdo;
protected $query;
protected $params = [];
public function __construct(PDO $pdo) {
$this-pdo = $pdo;
}
public function select($table, $columns = ['*']) {
$this-query = SELECT 、implode(', ', $columns) 、 FROM $table;
return $this;
}
public function where($column, $value, $operator = '=') {
$param = ':' 、str_replace('.', '_', $column);
$this-query .= WHERE $column $operator $param;
$this-params[$param] = $value;
return $this;
}
public function limit($limit, $offset = 0) {
$this-query .= LIMIT $offset, $limit;
return $this;
}
public function get() {
$stmt = $this-pdo-prepare($this-query);
$stmt-execute($this-params);
return $stmt-fetchAll();
}
public function first() {
$result = $this-limit(1)-get();
return $result[0] ?? null;
}
}
3、事务管理增强
php
trait TransactionTrait {
public function beginTransaction() {
return $this-pdo-beginTransaction();
}
public function commit() {
return $this-pdo-commit();
}
public function rollBack() {
return $this-pdo-rollBack();
}
public function transaction(callable $callback) {
$this-beginTransaction();
try {
$result = $callback($this);
$this-commit();
return $result;
} catch (Exception $e) {
$this-rollBack();
throw $e;
}
}
}
4、模型基类
php
abstract class Model {
protected $pdo;
protected $table;
protected $primaryKey = 'id';
public function __construct(PDO $pdo) {
$this-pdo = $pdo;
}
public function find($id) {
$stmt = $this-pdo-prepare(
SELECT * FROM {$this-table} WHERE {$this-primaryKey} = :id
);
$stmt-execute(['id' = $id]);
return $stmt-fetch();
}
public function create(array $data) {
$columns = implode(', ', array_keys($data));
$placeholders = ':' 、implode(', :', array_keys($data));
$stmt = $this-pdo-prepare(
INSERT INTO {$this-table} ($columns) VALUES ($placeholders)
);
$stmt-execute($data);
return $this-pdo-lastInsertId();
}
public function update($id, array $data) {
$set = [];
foreach ($data as $key = $value) {
$set[] = $key = :$key;
}
$set = implode(', ', $set);
$stmt = $this-pdo-prepare(
UPDATE {$this-table} SET $set WHERE {$this-primaryKey} = :id
);
$data['id'] = $id;
return $stmt-execute($data);
}
}
5、连接池实现(可选)
php
class ConnectionPool {
private $pool = [];
private $config;
private $maxConnections;
public function __construct($config, $maxConnections = 10) {
$this-config = $config;
$this-maxConnections = $maxConnections;
}
public function getConnection() {
if (!empty($this-pool)) {
return array_pop($this-pool);
}
if (count($this-pool) < $this-maxConnections) {
return new PDO(
$this-config['dsn'],
$this-config['username'],
$this-config['password'],
$this-config['options']
);
}
throw new Exception(连接池已满);
}
public function releaseConnection(PDO $connection) {
if (count($this-pool) < $this-maxConnections) {
$this-pool[] = $connection;
}
}
}
6、使用示例
php
// 初始化数据库连接
$db = new Database('localhost', 'test_db', 'username', 'password');
// 使用查询构建器
$users = (new QueryBuilder($db-getConnection()))
-select('users')
-where('age', 25, '')
-limit(10)
-get();
// 使用事务
$db-transaction(function($pdo) {
$stmt = $pdo-prepare(UPDATE accounts SET balance = balance 100 WHERE id = 1);
$stmt-execute();
$stmt = $pdo-prepare(UPDATE accounts SET balance = balance + 100 WHERE id = 2);
$stmt-execute();
});
// 使用模型
class User extends Model {
protected $table = 'users';
}
$userModel = new User($db-getConnection());
$user = $userModel-find(1);
最佳实践
1、始终使用预处理语句防止 SQL 注入
2、设置适当的错误处理模式
3、合理管理数据库连接
4、使用事务确保数据一致性
5、实现适当的连接超时和重试机制
这样的二次开发可以让 PDO 更加符合项目的具体需求,同时保持代码的整洁和可维护性。
📣 商家广告:





0
IP地址: 36.233.42.18
搜索次数: 0
提问时间: 2025-11-10 16:44:53
🛒 域名购买:
wz.chat
pcks.cn
guzun.cn
6444.com.cn
4.bj.cn
lv.gs
j-f.com.cn
wc.chat
z-j.net
naiwang.com.cn
❓️ 热门提问:
科创屏蔽机柜
机房防爆灯有什么要求
中国的虚拟主机
包装盒设计的网站
vps自建cdn
手机怎么用vps
云服务器租借
代理服务器美国
免费轻量云服务器
ftp部署服务器
豌豆Ai站群搜索引擎系统
🌐 域名评估:
ogau.cn
87.gold
pp.chat
mm.gs.cn
trump.tw.cn
trump.cq.cn
67.cx
n.sd.cn
aaaa.gd.cn
su8.gs.cn
⛏ 最新挖掘:
凯里酸汤鱼
贵阳烤脑花
都匀毛尖茶
花溪牛肉粉
贵阳烤生蚝
贵阳烤豆腐
贵阳纸包鱼
贵阳特色菜
🖌 热门作画:
🤝 关于我们:
豌豆Ai
域名
建站
站群
留痕
推广
评估
源码
开发Ai
工具
日记
价格
加盟
广告
流量
留言
联系
🗨 加入群聊:
🔗 友情链接:
香港搜尋引擎
网站搭建培训
ai提问
🧰 站长工具:
Ai工具 whois查询 搜索
📢 温馨提示:本站所有问答由Ai自动创作,内容仅供参考,若有误差请用“联系”里面信息通知我们人工修改或删除。
👉 技术支持:本站由豌豆Ai提供技术支持,使用的最新版:《豌豆Ai站群搜索引擎系统 V.25.10.25》搭建本站。