共计 6230 个字符,预计需要花费 16 分钟才能阅读完成。
摘要
将 PDO 封装成 PHP 类进行调用有很多益处,包含:
1、封装性和抽象性: 通过将 PDO 封装到一个类中,您能够将数据库操作逻辑与应用程序的其余局部拆散开来,进步了代码的组织性和可维护性。这样,您只需在一个中央保护数据库连贯和查问逻辑,而不用在整个应用程序中分布数据库代码。
2、重用性: 将数据库操作封装成类使得这些操作能够在应用程序的不同局部重复使用,而无需反复编写雷同的代码。这有助于缩小代码冗余,提高效率。
3、安全性: 通过类的办法来执行数据库操作,能够轻松地施行预处理语句,从而缩小了 SQL 注入攻打的危险。类还能够提供错误处理机制,使您可能更容易地解决数据库谬误。
4、可扩展性: 应用类封装数据库操作,能够轻松地扩大和保护应用程序。如果须要增加新的数据库操作或更改现有的操作,只需批改类中的相应办法而不用更改应用程序的其余局部。
5、清晰的接口: 类提供了一个清晰的接口,使其余开发人员可能更容易地了解和应用数据库操作。这有助于团队合作和代码保护。
将 PDO 封装成 PHP 类能够进步代码的可维护性、可重用性和安全性,同时升高了代码的耦合度,使数据库操作更容易治理和扩大。这是一个良好的软件工程实际,特地实用于中大型和简单的应用程序。
类文件
Database.php
以下是应用 Chatgpt 生成的操作类,然而我做了 30% 的批改和优化。
<?php | |
/** | |
* Title:PDO 数据库操作类 | |
* Author:TANKING | |
* Blog:https://segmentfault.com/u/tanking | |
* Date:2023-09-18 | |
*/ | |
class Database | |
{ | |
private $host; | |
private $username; | |
private $password; | |
private $database; | |
private $pdo; | |
private $error = null; | |
public function __construct($host, $username, $password, $database) | |
{ | |
$this->host = $host; | |
$this->username = $username; | |
$this->password = $password; | |
$this->database = $database; | |
$this->connect();} | |
// 获取错误信息 | |
public function getError() | |
{return $this->error;} | |
// 连贯数据库 | |
private function connect() | |
{$dsn = "mysql:host={$this->host};dbname={$this->database}"; | |
try {$this->pdo = new PDO($dsn, $this->username, $this->password); | |
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); | |
} catch (PDOException $e) {die("Connection failed:" . $e->getMessage()); | |
} | |
} | |
// 插入数据 | |
public function insert($table, $data) | |
{ | |
try {$columns = implode(",", array_keys($data)); | |
$values = ":" . implode(", :", array_keys($data)); | |
$sql = "INSERT INTO $table ($columns) VALUES ($values)"; | |
$stmt = $this->pdo->prepare($sql); | |
$result = $stmt->execute($data); | |
if (!$result) {$this->error = $stmt->errorInfo(); | |
} | |
return $result; | |
} catch (PDOException $e) { | |
// 解决数据库异样 | |
$this->error = $e->getMessage(); | |
return FALSE; | |
} | |
} | |
// 更新数据 | |
public function update($table, $data, $where) | |
{ | |
try { | |
$set = ""; | |
foreach ($data as $key => $value) {$set .= "$key = :$key,";} | |
$set = rtrim($set, ','); | |
$sql = "UPDATE $table SET $set WHERE $where"; | |
$stmt = $this->pdo->prepare($sql); | |
$result = $stmt->execute($data); | |
if (!$result) {$this->error = $stmt->errorInfo(); | |
} | |
return $result; | |
} catch (PDOException $e) { | |
// 解决数据库异样 | |
$this->error = $e->getMessage(); | |
return FALSE; | |
} | |
} | |
// 删除数据 | |
public function delete($table, $where) | |
{ | |
try { | |
$sql = "DELETE FROM $table WHERE $where"; | |
$stmt = $this->pdo->prepare($sql); | |
$result = $stmt->execute(); | |
if($stmt->rowCount() === 0) { | |
// 没有受影响的记录 | |
$this->error = '没有受影响的记录'; | |
return FALSE; | |
}else {return $result;} | |
} catch (PDOException $e) { | |
// 解决数据库异样 | |
$this->error = $e->getMessage(); | |
return FALSE; | |
} | |
} | |
// 查问一条数据 | |
public function queryOne($table, $conditions = []) | |
{$whereClause = $this->buildWhereClause($conditions); | |
$sql = "SELECT * FROM $table $whereClause LIMIT 1"; | |
try {$stmt = $this->pdo->prepare($sql); | |
$stmt->execute($conditions); | |
return $stmt->fetch(PDO::FETCH_ASSOC); | |
} catch (PDOException $e) { | |
// 解决数据库异样 | |
$this->error = $e->getMessage(); | |
return FALSE; | |
} | |
} | |
// 查问所有数据 | |
public function queryAll($table, $conditions = []) | |
{$whereClause = $this->buildWhereClause($conditions); | |
$sql = "SELECT * FROM $table $whereClause"; | |
try {$stmt = $this->pdo->prepare($sql); | |
$stmt->execute($conditions); | |
return $stmt->fetchAll(PDO::FETCH_ASSOC); | |
} catch (PDOException $e) { | |
// 解决数据库异样 | |
$this->error = $e->getMessage(); | |
return FALSE; | |
} | |
} | |
// 执行原生 SQL 语句 | |
public function executeSQL($sql, $params = []) | |
{ | |
try {$stmt = $this->pdo->prepare($sql); | |
$result = $stmt->execute($params); | |
if (!$result) { | |
// 执行失败 | |
$this->error = $stmt->errorInfo(); | |
return FALSE; | |
} | |
return $stmt; | |
} catch (PDOException $e) { | |
// 解决数据库异样 | |
$this->error = $stmt->errorInfo(); | |
return FALSE; | |
} | |
} | |
// 数据绑定 | |
private function buildWhereClause($conditions) | |
{if (empty($conditions)) {return '';} | |
$where = 'WHERE'; | |
foreach ($conditions as $key => $value) {$where .= "$key = :$key AND";} | |
$where = rtrim($where, 'AND'); | |
return $where; | |
} | |
} |
实例
配置文件 Db.php
<?php | |
/** | |
* Title:数据库配置 | |
* Author:TANKING | |
* Blog:https://segmentfault.com/u/tanking | |
* Date:2023-09-18 | |
*/ | |
$DbConfig = array( | |
'db_host' => 'xxx', // 数据库服务器 | |
'db_name' => 'xxx', // 数据库名 | |
'db_user' => 'xxx', // 数据库账号 | |
'db_pwd' => 'xxx', // 数据库明码 | |
); | |
include 'Database.php'; | |
?> |
以下实例应用一个名为 artcles
的数据库表进行操作演示。
插入数据 insert.php
<?php | |
// 编码 | |
header("Content-type:application/json"); | |
// 数据库配置 | |
include 'Db.php'; | |
// 连贯数据库 | |
$db = new Database($DbConfig['db_host'], $DbConfig['db_user'], $DbConfig['db_pwd'], $DbConfig['db_name']); | |
// 插入数据 | |
$data = ['aid' => rand(100000,999999), | |
'title' => 'sdfgsadg', | |
'tag' => 'ceshi', | |
'content' => '这是内容', | |
'author' => 'TANKING' | |
]; | |
$insertArtcle = $db->insert('artcles', $data); | |
if($insertArtcle){echo '插入胜利';}else{echo '失败!' . $db->getError(); | |
} | |
?> |
更新数据 update.php
<?php | |
// 编码 | |
header("Content-type:application/json"); | |
// 数据库配置 | |
include 'Db.php'; | |
// 连贯数据库 | |
$db = new Database($DbConfig['db_host'], $DbConfig['db_user'], $DbConfig['db_pwd'], $DbConfig['db_name']); | |
// 更新 | |
$updateData = ['tag' => '测试']; | |
$where = 'id = 19'; | |
$updateArtcle = $db->update('artcles', $updateData, $where); | |
if($updateArtcle){echo '更新胜利!';}else{echo '更新失败!' . $db->getError(); | |
} | |
?> |
删除数据 delete.php
<?php | |
// 编码 | |
header("Content-type:application/json"); | |
// 数据库配置 | |
include 'Db.php'; | |
// 连贯数据库 | |
$db = new Database($DbConfig['db_host'], $DbConfig['db_user'], $DbConfig['db_pwd'], $DbConfig['db_name']); | |
// 删除 | |
$where = 'id = 11'; | |
$deleteArtcle = $db->delete('artcles', $where); | |
if($deleteArtcle){echo '删除胜利!';}else{echo '删除失败!' . $db->getError(); | |
} | |
?> |
查问一条数据 queryOne.php
<?php | |
// 编码 | |
header("Content-type:application/json"); | |
// 数据库配置 | |
include 'Db.php'; | |
// 连贯数据库 | |
$db = new Database($DbConfig['db_host'], $DbConfig['db_user'], $DbConfig['db_pwd'], $DbConfig['db_name']); | |
// 查问一条数据 | |
$conditions = ['id' => 18]; | |
$getArtcle = $db->queryOne('artcles', $conditions); | |
if($getArtcle){echo json_encode($getArtcle); | |
}else{echo '查问失败!' . $db->getError(); | |
} | |
?> |
查问所有数据 queryAll.php
<?php | |
// 编码 | |
header("Content-type:application/json"); | |
// 数据库配置 | |
include 'Db.php'; | |
// 连贯数据库 | |
$db = new Database($DbConfig['db_host'], $DbConfig['db_user'], $DbConfig['db_pwd'], $DbConfig['db_name']); | |
// 查问所有数据 | |
$conditions = []; | |
$getArtcles = $db->queryAll('artcles', $conditions); | |
if($getArtcles){echo json_encode($getArtcles); | |
}else{echo '查问失败!' . $db->getError(); | |
} | |
?> |
执行原生 SQL 语句
// 插入 | |
$sql = "INSERT INTO artcles (aid, title, tag, content, author) VALUES (:aid, :title, :tag, :content, :author)"; | |
$params = [':aid' => rand(100000,999999), | |
':title' => '这是题目' . uniqid(), | |
':tag' => 'tag' . rand(0,9), | |
':content' => '这是内容' . uniqid(), | |
':author' => 'TANKING' | |
]; | |
// 更新 | |
$sql = "UPDATE artcles SET title = :title WHERE id = :id"; | |
$params = [ | |
':id' => 22, | |
':title' => '这是题目_已更新', | |
]; | |
// 删除 | |
$sql = "DELETE FROM artcles WHERE id = :id"; | |
$params = [':id' => 20]; | |
// 查问 | |
$sql = "SELECT * FROM artcles"; | |
try {$stmt = $db->executeSQL($sql); | |
if ($stmt) {$result = $stmt->fetchAll(PDO::FETCH_ASSOC); | |
if (empty($result)) { | |
// 没有匹配的后果 | |
echo "没有匹配的后果"; | |
} else {echo json_encode($result); | |
} | |
} else {echo "查问失败,错误信息:" . json_encode($db->getError()); | |
} | |
} catch (DatabaseException $e) { | |
// 查问失败 | |
echo $e->getMessage();} |
作者
TANKING