PHP封裝PDO實現(xiàn)操作MySql數(shù)據(jù)庫
摘要
數(shù)據(jù)庫操作類可以封裝數(shù)據(jù)庫連接和操作,使代碼更易于維護和擴展。它們提供了一種組織代碼的方法,將數(shù)據(jù)庫相關(guān)的功能放在一個類中,以便于復(fù)用。
良好的數(shù)據(jù)庫操作類可以提供一定程度的安全性,通過參數(shù)化查詢或準備語句來防止SQL注入攻擊。這有助于保護數(shù)據(jù)庫免受惡意輸入的影響。
良好的數(shù)據(jù)庫操作類可以提供一定程度的安全性,通過參數(shù)化查詢或準備語句來防止SQL注入攻擊。這有助于保護數(shù)據(jù)庫免受惡意輸入的影響。
數(shù)據(jù)庫操作類有助于提高PHP應(yīng)用程序的可維護性、安全性和性能,同時促進代碼的重用和更好的代碼組織。然而,選擇適合項目需求的數(shù)據(jù)庫操作類以及正確使用它們非常重要。
Database.php
<?php
/**
* PHP PDO MySQL數(shù)據(jù)庫操作類
* 作者:TANKING
* 時間:2023-10-12
* 博客:https://segmentfault.com/u/tanking
*/
class DB_API {
private $pdo;
private $error;
// 連接數(shù)據(jù)庫
public function __construct($config) {
$dsn = "mysql:host={$config['db_host']};port={$config['db_port']};dbname={$config['db_name']}";
try {
$this->pdo = new PDO($dsn, $config['db_user'], $config['db_pass']);
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
$this->error = $e->getMessage();
}
}
// 插入
public function add($table, $data) {
try {
$columns = implode(', ', array_keys($data));
$values = implode(', :', array_keys($data));
$query = "INSERT INTO $table ($columns) VALUES (:$values)";
$stmt = $this->pdo->prepare($query);
$stmt->execute($data);
return $this->pdo->lastInsertId();
} catch (PDOException $e) {
$this->error = $e->getMessage();
return false;
}
}
// 更新
public function update($table, $where, $data) {
try {
// 構(gòu)建SET子句
$set = '';
foreach ($data as $key => $value) {
$set .= "$key = :$key, ";
}
$set = rtrim($set, ', ');
// 構(gòu)建WHERE子句
$whereClause = '';
foreach ($where as $key => $value) {
$whereClause .= "$key = :where_$key AND ";
}
$whereClause = rtrim($whereClause, 'AND ');
// 構(gòu)建SQL查詢
$query = "UPDATE $table SET $set WHERE $whereClause";
// 創(chuàng)建預(yù)處理語句
$stmt = $this->pdo->prepare($query);
// 綁定更新數(shù)據(jù)的參數(shù)
foreach ($data as $key => $value) {
$stmt->bindValue(":$key", $value);
}
// 綁定WHERE條件的參數(shù)
foreach ($where as $key => $value) {
$stmt->bindValue(":where_$key", $value);
}
// 執(zhí)行預(yù)處理語句
$stmt->execute();
// 操作成功
return true;
} catch (PDOException $e) {
$this->error = $e->getMessage();
// 操作失敗
return false;
}
}
// 刪除
public function delete($table, $where, $params = array()) {
try {
// 構(gòu)建WHERE子句
$whereClause = '';
foreach ($where as $key => $value) {
$whereClause .= "$key = :$key AND ";
}
$whereClause = rtrim($whereClause, 'AND ');
// 構(gòu)建SQL查詢
$query = "DELETE FROM $table WHERE $whereClause";
// 創(chuàng)建預(yù)處理語句
$stmt = $this->pdo->prepare($query);
// 綁定WHERE條件的參數(shù)
foreach ($where as $key => $value) {
$stmt->bindValue(":$key", $value);
}
// 執(zhí)行預(yù)處理語句
$stmt->execute();
// 操作成功
return true;
} catch (PDOException $e) {
$this->error = $e->getMessage();
// 操作失敗
return false;
}
}
// 查詢
public function select($table, $fields = "*", $conditions = null, $likeConditions = null, $orderBy = null, $limit = null, $params = array()) {
try {
// 構(gòu)建SELECT子句
if (is_array($fields)) {
$fields = implode(', ', $fields);
} elseif ($fields === "*") {
$fields = "*";
} else {
$fields = "";
}
// 構(gòu)建WHERE子句
$whereClause = '';
if (!is_null($conditions) && is_array($conditions)) {
foreach ($conditions as $key => $value) {
$whereClause .= "$key = :$key AND ";
}
$whereClause = rtrim($whereClause, 'AND ');
}
// 合并LIKE條件
if (!is_null($likeConditions) && is_array($likeConditions)) {
if (!empty($whereClause)) {
$whereClause .= ' AND ';
}
foreach ($likeConditions as $key => $value) {
$whereClause .= "$key LIKE :like_$key AND ";
$params[":like_$key"] = $value;
}
$whereClause = rtrim($whereClause, 'AND ');
}
// 構(gòu)建ORDER BY子句
$orderByClause = '';
if (!is_null($orderBy) && is_array($orderBy)) {
$orderByClause = "ORDER BY " . implode(', ', $orderBy);
}
// 構(gòu)建LIMIT子句
$limitClause = '';
if (!is_null($limit)) {
$limitClause = "LIMIT $limit";
}
// 構(gòu)建SQL查詢
$query = "SELECT $fields FROM $table";
if (!empty($whereClause)) {
$query .= " WHERE $whereClause";
}
if (!empty($orderByClause)) {
$query .= " $orderByClause";
}
if (!empty($limitClause)) {
$query .= " $limitClause";
}
// 創(chuàng)建預(yù)處理語句
$stmt = $this->pdo->prepare($query);
// 綁定參數(shù)
if (!is_null($conditions) && is_array($conditions)) {
foreach ($conditions as $key => $value) {
$stmt->bindValue(":$key", $value);
}
}
if (!is_null($likeConditions) && is_array($likeConditions)) {
foreach ($likeConditions as $key => $value) {
$stmt->bindValue(":like_$key", $value);
}
}
// 執(zhí)行預(yù)處理語句
$stmt->execute();
// 獲取查詢結(jié)果
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $result; // 返回查詢結(jié)果數(shù)組
} catch (PDOException $e) {
$this->error = $e->getMessage();
return false; // 操作失敗
}
}
// 執(zhí)行原生SQL語句
public function execQuery($query, $params = array()) {
try {
// 創(chuàng)建預(yù)處理語句
$stmt = $this->pdo->prepare($query);
// 綁定參數(shù)
foreach ($params as $key => $value) {
$stmt->bindValue($key, $value);
}
// 執(zhí)行預(yù)處理語句
$stmt->execute();
// 操作成功
return true;
} catch (PDOException $e) {
$this->error = $e->getMessage();
// 操作失敗
return false;
}
}
// 錯誤信息
public function errorMsg() {
return $this->error;
}
}Db.php
<?php
// 引入操作類
include 'Database.php';
// 配置文件
$config = array(
'db_host' => 'localhost',
'db_port' => 3306,
'db_name' => 'xxx',
'db_user' => 'xxx',
'db_pass' => 'xxx'
);
?>使用示例
以表名為 test_table 為示例作為示例代碼。
創(chuàng)建表SQL:
CREATE TABLE `test_table` ( `id` int(10) PRIMARY KEY AUTO_INCREMENT NOT NULL, `title` varchar(32) NOT NULL, `content` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
insert示例
<?php
// 引入配置
include 'Db.php';
// 實例化
$db = new DB_API($config);
// 數(shù)據(jù)
$insertData = array(
'title' => 'this is title',
'content' => 'this is content',
);
// 執(zhí)行
$insertSQL = $db->add('test_table', $insertData);
// 結(jié)果
if ($insertSQL) {
// 成功
echo '插入成功,ID是:' . $insertSQL;
} else {
// 失敗
echo '插入失敗,原因:' . $db->errorMsg();
}
?>update示例
<?php
// 引入配置
include 'Db.php';
// 實例化
$db = new DB_API($config);
// 條件
// 只支持=,不支持>,<,>=,<=之類的
// 如需更復(fù)雜的條件請使用執(zhí)行原生語句的方法
$where = array(
'id' => '1'
);
// 數(shù)據(jù)
$updateData = array(
'content' => 'content is updated'
);
// 執(zhí)行
$updatedSQL = $db->update('test_table', $where, $updateData);
// 結(jié)果
if ($updatedSQL) {
// 成功
echo '更新成功';
} else {
// 失敗
echo '更新失敗,原因:' . $db->errorMsg();
}
?>delete示例
<?php
// 引入配置
include 'Db.php';
// 實例化
$db = new DB_API($config);
// 條件
$where = array(
'id' => 4,
);
// 執(zhí)行
$deleteSQL = $db->delete('test_table', $where);
// 結(jié)果
if ($deleteSQL) {
// 成功
echo '刪除成功';
} else {
// 失敗
echo '刪除失敗,原因:' . $db->errorMsg();
}
?>select示例
<?php
// 引入配置
include 'Db.php';
// 實例化
$db = new DB_API($config);
// 使用方法
// $db->select('表名', ['字段1','字段2',...], where條件, LIKE條件, ORDER條件, LIKIT條件);
// 如果查詢所有字段,使用'*'代替數(shù)組
// $db->select('表名', '*', where條件, LIKE條件, ORDER條件, LIKIT條件);
// 無需使用的條件傳遞null
// $db->select('表名', '*', where條件, null, null, null);
// 查詢所有字段,沒有查詢條件
$selectSQL = $db->select('test_table', '*');
// 查詢指定字段,沒有查詢條件
// $selectSQL = $db->select('test_table', ['id', 'title']);
// 根據(jù)以下條件
// 查詢所有字段
// $where = array(
// 'id' => 3
// );
// $selectSQL = $db->select('test_table', '*', $where);
// 根據(jù)以下條件
// 查詢指定字段
// $where = array(
// 'id' => 3
// );
// $selectSQL = $db->select('test_table', ['title'], $where);
// 使用LIKE條件
// 如果沒有where條件就直接傳入null
// '*'是查詢所有字段,如需查詢指定字段傳入['字段1','字段2',....]
// $likeWhere = array(
// 'title' => '%一帶一路%'
// );
// $selectSQL = $db->select('test_table', '*', null, $likeWhere);
// 使用where條件和LIKE條件
// '*'是查詢所有字段,如需查詢指定字段傳入['字段1','字段2',....]
// $where = array(
// 'id' => 3
// );
// $likeWhere = array(
// 'title' => '%一帶一路%'
// );
// $selectSQL = $db->select('test_table', '*', $where, $likeWhere);
// 使用排序條件
// $orderBy = array('id DESC');
// $selectSQL = $db->select('test_table', '*', null, null, $orderBy);
// 使用限制條件
// $limit = 2; // 取2條
// $limit = '0,3'; // 第1條開始,取3條
// $limit = '5,2'; // 第5條開始,取2條
// $selectSQL = $db->select('test_table', '*', null, null, null, $limit);
// 結(jié)果
if ($selectSQL) {
// 成功
echo json_encode($selectSQL, JSON_UNESCAPED_UNICODE);
} else {
// 失敗
echo '查詢失敗,原因:' . $db->errorMsg();
}
?>執(zhí)行原生語句示例
<?php
// 引入配置
include 'Db.php';
// 實例化
$db = new DB_API($config);
// SQL語句
$query = "INSERT INTO test_table (title, content) VALUES (:title, :content)";
// 數(shù)據(jù)綁定
$params = array(
':title' => 'New Title By execQuery',
':content' => 'New Content By execQuery',
);
// 執(zhí)行
$querySQL = $db->execQuery($query, $params);
// 結(jié)果
if ($querySQL) {
// 成功
echo 'SQL執(zhí)行成功!';
} else {
// 失敗
echo 'SQL執(zhí)行失敗,原因:' . $db->errorMsg();
}
?>以上就是PHP封裝PDO實現(xiàn)操作MySql數(shù)據(jù)庫的詳細內(nèi)容,更多關(guān)于PHP操作MySql的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
PHP多維數(shù)組遍歷方法(2種實現(xiàn)方法)
這篇文章主要介紹了PHP多維數(shù)組遍歷方法,實例分析了2種多維數(shù)組的遍歷技巧,包括簡單的foreach遍歷與遞歸操作遍歷實現(xiàn)方法,需要的朋友可以參考下2015-12-12
PHP中調(diào)用C/C++制作的動態(tài)鏈接庫的教程
這篇文章主要介紹了PHP中調(diào)用C/C++制作的動態(tài)鏈接庫的教程,文中還簡單地提到了gcc編譯器下動態(tài)鏈接庫的制作方法,需要的朋友可以參考下2016-03-03
PHP中使用jQuery+Ajax實現(xiàn)分頁查詢多功能操作(示例講解)
下面小編就為大家?guī)硪黄狿HP中使用jQuery+Ajax實現(xiàn)分頁查詢多功能操作(示例講解)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-09-09

