豌豆Ai站群搜索引擎系统 V.25.10.25 网址:www.wd.chat

🗣 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 更加符合项目的具体需求,同时保持代码的整洁和可维护性。

Ai作答

📣 商家广告


月饼

高防vps

中国域名

起名

星座


0

IP地址: 155.10.98.204

搜索次数: 24

提问时间: 2025-11-02 23:07:44

🛒 域名购买

❓️ 热门提问

🌐 域名评估

最新挖掘

🖌 热门作画

🤝 关于我们

🗨 加入群聊

🔗 友情链接

🧰 站长工具
📢

温馨提示

本站所有 问答 均由Ai自动分析整理,内容仅供参考,若有误差请用“联系”里面信息通知我们人工修改或删除。

👉

技术支持

本站由 🟢 豌豆Ai 提供技术支持,使用的最新版: 豌豆Ai站群搜索引擎系统 V.25.10.25 搭建本站。

上一篇 84636 84637 84638 下一篇