news 2026/6/4 3:28:56

PHP对象关系映射与PDO实战

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
PHP对象关系映射与PDO实战

PHP对象关系映射与PDO实战

PDO是PHP数据库操作的标准方式。它提供了一个统一的接口来操作不同类型的数据库,同时预处理语句可以防止SQL注入。今天说说PDO的高级用法和ORM的实现思路。

先看看PDO的连接配置。字符集一定要用utf8mb4,不然存emoji会报错。

```php
// PDO连接
$dsn = 'mysql:host=localhost;dbname=test;charset=utf8mb4';
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci",
];

$pdo = new PDO($dsn, 'root', '', $options);

// 获取查询结果
$stmt = $pdo->query("SELECT * FROM users LIMIT 10");
$users = $stmt->fetchAll(); // 获取所有行
$user = $stmt->fetch(); // 获取单行
$count = $stmt->fetchColumn(); // 获取单列

// 不同的获取模式
$stmt = $pdo->query("SELECT id, name FROM users");
$byId = $stmt->fetchAll(PDO::FETCH_KEY_PAIR); // 第一列做键,第二列做值
print_r($byId);

$stmt = $pdo->query("SELECT * FROM users");
$objects = $stmt->fetchAll(PDO::FETCH_OBJ); // 对象形式
foreach ($objects as $obj) {
echo "{$obj->name}\n";
}
?>
```

事务处理在涉及多个相关操作的场景中必不可少。

```php
function processOrder(PDO $pdo, int $userId, array $items): array
{
try {
$pdo->beginTransaction();

// 计算总价
$total = 0;
foreach ($items as $item) {
$total += $item['price'] * $item['quantity'];
}

// 创建订单
$stmt = $pdo->prepare(
"INSERT INTO orders (user_id, total, status, created_at) VALUES (?, ?, 'pending', NOW())"
);
$stmt->execute([$userId, $total]);
$orderId = $pdo->lastInsertId();

// 插入订单项
$stmt = $pdo->prepare(
"INSERT INTO order_items (order_id, product_id, quantity, price) VALUES (?, ?, ?, ?)"
);
foreach ($items as $item) {
$stmt->execute([$orderId, $item['product_id'], $item['quantity'], $item['price']]);
}

// 扣减库存
$stmt = $pdo->prepare(
"UPDATE products SET stock = stock - ? WHERE id = ? AND stock >= ?"
);
foreach ($items as $item) {
$stmt->execute([$item['quantity'], $item['product_id'], $item['quantity']]);
if ($stmt->rowCount() === 0) {
throw new RuntimeException("商品库存不足: {$item['product_id']}");
}
}

$pdo->commit();

return ['order_id' => $orderId, 'total' => $total, 'status' => 'pending'];

} catch (Exception $e) {
$pdo->rollBack();
throw $e;
}
}
?>
```

自定义PDO可以封装常用的查询模式,比如根据ID查询、分页查询等。

```php
class Db
{
private PDO $pdo;

public function __construct(PDO $pdo)
{
$this->pdo = $pdo;
}

public function find(string $table, int $id): ?array
{
$stmt = $this->pdo->prepare("SELECT * FROM {$table} WHERE id = ?");
$stmt->execute([$id]);
$result = $stmt->fetch();
return $result ?: null;
}

public function findAll(string $table, array $conditions = []): array
{
$sql = "SELECT * FROM {$table}";
$params = [];

if (!empty($conditions)) {
$wheres = [];
foreach ($conditions as $column => $value) {
$wheres[] = "{$column} = ?";
$params[] = $value;
}
$sql .= " WHERE " . implode(' AND ', $wheres);
}

$sql .= " ORDER BY id DESC";

$stmt = $this->pdo->prepare($sql);
$stmt->execute($params);
return $stmt->fetchAll();
}

public function insert(string $table, array $data): int
{
$columns = implode(', ', array_keys($data));
$placeholders = implode(', ', array_fill(0, count($data), '?'));

$stmt = $this->pdo->prepare(
"INSERT INTO {$table} ({$columns}) VALUES ({$placeholders})"
);
$stmt->execute(array_values($data));

return (int)$this->pdo->lastInsertId();
}

public function update(string $table, int $id, array $data): int
{
$sets = [];
$params = [];
foreach ($data as $column => $value) {
$sets[] = "{$column} = ?";
$params[] = $value;
}
$params[] = $id;

$stmt = $this->pdo->prepare(
"UPDATE {$table} SET " . implode(', ', $sets) . " WHERE id = ?"
);
$stmt->execute($params);

return $stmt->rowCount();
}

public function delete(string $table, int $id): int
{
$stmt = $this->pdo->prepare("DELETE FROM {$table} WHERE id = ?");
$stmt->execute([$id]);
return $stmt->rowCount();
}

public function paginate(string $table, int $page = 1, int $perPage = 20, array $conditions = []): array
{
$offset = ($page - 1) * $perPage;
$where = '';
$params = [];

if (!empty($conditions)) {
$wheres = [];
foreach ($conditions as $column => $value) {
$wheres[] = "{$column} = ?";
$params[] = $value;
}
$where = " WHERE " . implode(' AND ', $wheres);
}

$countStmt = $this->pdo->prepare("SELECT COUNT(*) FROM {$table}{$where}");
$countStmt->execute($params);
$total = (int)$countStmt->fetchColumn();

$dataStmt = $this->pdo->prepare(
"SELECT * FROM {$table}{$where} ORDER BY id DESC LIMIT ? OFFSET ?"
);
$dataStmt->execute(array_merge($params, [$perPage, $offset]));
$items = $dataStmt->fetchAll();

return [
'items' => $items,
'total' => $total,
'page' => $page,
'per_page' => $perPage,
'total_pages' => ceil($total / $perPage),
'has_more' => $page * $perPage < $total,
];
}
}

$db = new Db($pdo);

// 使用
$user = $db->find('users', 1);
$users = $db->findAll('users', ['status' => 'active']);
$newId = $db->insert('users', ['name' => '张三', 'email' => 'test@test.com']);
$db->update('users', $newId, ['name' => '李四']);
$result = $db->paginate('users', 1, 20);
echo "总记录: {$result['total']}, 当前页: {$result['page']}\n";
?>
```

基于PDO可以构建一个简单的ORM。

```php
abstract class Model
{
protected static string $table = '';
protected static string $primaryKey = 'id';
protected array $attributes = [];
protected array $original = [];
protected array $dirty = [];

public function __construct(array $attributes = [])
{
$this->fill($attributes);
}

public function fill(array $attributes): void
{
foreach ($attributes as $key => $value) {
$this->attributes[$key] = $value;
}
$this->original = $this->attributes;
}

public function __get(string $name): mixed
{
return $this->attributes[$name] ?? null;
}

public function __set(string $name, mixed $value): void
{
$this->attributes[$name] = $value;
$this->dirty[$name] = true;
}

public function save(): bool
{
if (isset($this->attributes[static::$primaryKey])) {
return $this->update();
}
return $this->insert();
}

protected function insert(): bool
{
$db = static::getDb();
$id = $db->insert(static::$table, $this->attributes);
if ($id) {
$this->attributes[static::$primaryKey] = $id;
$this->original = $this->attributes;
$this->dirty = [];
return true;
}
return false;
}

protected function update(): bool
{
if (empty($this->dirty)) return true;

$data = [];
foreach ($this->dirty as $field => $_) {
$data[$field] = $this->attributes[$field];
}

$db = static::getDb();
$result = $db->update(
static::$table,
$this->attributes[static::$primaryKey],
$data
);

if ($result !== false) {
$this->original = $this->attributes;
$this->dirty = [];
return true;
}
return false;
}

// 为了演示,直接用静态方法
private static ?PDO $_db = null;
protected static function getDb(): Db
{
if (self::$_db === null) {
self::$_db = new Db(new PDO('mysql:host=localhost;dbname=test', 'root', ''));
}
return self::$_db;
}
}

class User extends Model
{
protected static string $table = 'users';
}

$user = new User(['name' => '张三', 'email' => 'test@test.com']);
$user->save();
echo "用户ID: {$user->id}\n";

$user->name = '李四';
$user->save();
echo "更新后: {$user->name}\n";
?>
```

PDO还有几个容易被忽略的功能。比如PDO::lastInsertId获取自增ID,rowCount获取影响行数,quote做安全转义(但不如预处理安全)。掌握了这些,PHP操作数据库就很顺手了。

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/6/4 3:28:56

把ESP32-CAM变成智能门铃:低成本实现局域网视频监控与人脸识别告警

用ESP32-CAM打造智能门铃&#xff1a;从硬件搭建到人脸识别告警全指南在智能家居设备价格居高不下的今天&#xff0c;自己动手打造一个功能完善的智能门铃系统不仅经济实惠&#xff0c;还能完全掌控数据隐私。ESP32-CAM模组凭借其内置Wi-Fi和摄像头的特性&#xff0c;成为实现这…

作者头像 李华
网站建设 2026/6/4 3:25:13

从Linux到MCU:给熟悉STM32的你,一份Zephyr RTOS快速上手指南

从Linux到MCU&#xff1a;给熟悉STM32的你&#xff0c;一份Zephyr RTOS快速上手指南如果你已经习惯了在STM32上编写裸机程序或使用FreeRTOS&#xff0c;现在正考虑尝试Zephyr RTOS&#xff0c;那么你可能会发现这个过渡比想象中要平滑得多。特别是对于那些有Linux开发经验的工程…

作者头像 李华
网站建设 2026/6/4 3:25:12

别再只用快速表计算了!Tableau同比环比分析的5种实战场景与避坑指南

Tableau同比环比分析的5种高阶场景与实战避坑指南当你已经能熟练使用Tableau的快速表计算完成基础同比环比分析时&#xff0c;是否遇到过这些困境&#xff1a;数据存在断档月份导致图表出现断层&#xff1f;需要对比非自然年度的财务周期&#xff1f;想在同一个视图里同时观察销…

作者头像 李华
网站建设 2026/6/4 3:22:27

线上 CPU 暴升 100%?一次关于 Python 闭包无侵入函数耗时与内存监测的惊险排查与调优实战

线上 CPU 暴升 100%&#xff1f;一次关于 Python 闭包无侵入函数耗时与内存监测的惊险排查与调优实战前言 生产环境突发 CPU 飙升。排查难度极大。原有日志粒度太粗。无法定位具体函数。我们需要高精度监测。必须无侵入式实现。不能修改业务代码。闭包是最佳方案。本文直接给出…

作者头像 李华
网站建设 2026/6/4 3:21:35

新手友好:通过快马生成你的第一个网络测速网页,轻松入门Web开发

快速体验 打开 InsCode(快马)平台 https://www.inscode.net输入框内输入如下内容&#xff1a; 请为编程新手生成一个基础网络测速页面代码。要求页面有一个显眼的“开始测速”按钮&#xff0c;点击后能计算并显示网络延迟&#xff08;Ping&#xff09;、下载速度和上传速度。…

作者头像 李华