博客 / 詳情

返回

PHP封裝的PDO操作MySQL數據庫操作類!簡單易用!

摘要

數據庫操作類可以封裝數據庫連接和操作,使代碼更易於維護和擴展。它們提供了一種組織代碼的方法,將數據庫相關的功能放在一個類中,以便於複用。

良好的數據庫操作類可以提供一定程度的安全性,通過參數化查詢或準備語句來防止SQL注入攻擊。這有助於保護數據庫免受惡意輸入的影響。

良好的數據庫操作類可以提供一定程度的安全性,通過參數化查詢或準備語句來防止SQL注入攻擊。這有助於保護數據庫免受惡意輸入的影響。

數據庫操作類有助於提高PHP應用程序的可維護性、安全性和性能,同時促進代碼的重用和更好的代碼組織。然而,選擇適合項目需求的數據庫操作類以及正確使用它們非常重要。

Database.php

<?php
    
    /**
     * PHP PDO MySQL數據庫操作類
     * 作者:TANKING
     * 時間:2023-10-12
     * 博客:https://segmentfault.com/u/tanking
     */

    class DB_API {
        private $pdo;
        private $error;
        
        // 連接數據庫
        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 {
                
                // 構建SET子句
                $set = '';
                foreach ($data as $key => $value) {
                    $set .= "$key = :$key, ";
                }
                $set = rtrim($set, ', ');
        
                // 構建WHERE子句
                $whereClause = '';
                foreach ($where as $key => $value) {
                    $whereClause .= "$key = :where_$key AND ";
                }
                $whereClause = rtrim($whereClause, 'AND ');
        
                // 構建SQL查詢
                $query = "UPDATE $table SET $set WHERE $whereClause";
        
                // 創建預處理語句
                $stmt = $this->pdo->prepare($query);
        
                // 綁定更新數據的參數
                foreach ($data as $key => $value) {
                    $stmt->bindValue(":$key", $value);
                }
        
                // 綁定WHERE條件的參數
                foreach ($where as $key => $value) {
                    $stmt->bindValue(":where_$key", $value);
                }
    
                // 執行預處理語句
                $stmt->execute();
                
                // 操作成功
                return true;
        
            } catch (PDOException $e) {
                $this->error = $e->getMessage();
                
                // 操作失敗
                return false;
            }
        }
    
        // 刪除
        public function delete($table, $where, $params = array()) {
            try {
                // 構建WHERE子句
                $whereClause = '';
                foreach ($where as $key => $value) {
                    $whereClause .= "$key = :$key AND ";
                }
                $whereClause = rtrim($whereClause, 'AND ');
        
                // 構建SQL查詢
                $query = "DELETE FROM $table WHERE $whereClause";
        
                // 創建預處理語句
                $stmt = $this->pdo->prepare($query);
        
                // 綁定WHERE條件的參數
                foreach ($where as $key => $value) {
                    $stmt->bindValue(":$key", $value);
                }
        
                // 執行預處理語句
                $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 {
                // 構建SELECT子句
                if (is_array($fields)) {
                    $fields = implode(', ', $fields);
                } elseif ($fields === "*") {
                    $fields = "*";
                } else {
                    $fields = "";
                }
        
                // 構建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 ');
                }
        
                // 構建ORDER BY子句
                $orderByClause = '';
                if (!is_null($orderBy) && is_array($orderBy)) {
                    $orderByClause = "ORDER BY " . implode(', ', $orderBy);
                }
        
                // 構建LIMIT子句
                $limitClause = '';
                if (!is_null($limit)) {
                    $limitClause = "LIMIT $limit";
                }
        
                // 構建SQL查詢
                $query = "SELECT $fields FROM $table";
                if (!empty($whereClause)) {
                    $query .= " WHERE $whereClause";
                }
                if (!empty($orderByClause)) {
                    $query .= " $orderByClause";
                }
                if (!empty($limitClause)) {
                    $query .= " $limitClause";
                }
        
                // 創建預處理語句
                $stmt = $this->pdo->prepare($query);
        
                // 綁定參數
                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);
                    }
                }
        
                // 執行預處理語句
                $stmt->execute();
        
                // 獲取查詢結果
                $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
                return $result; // 返回查詢結果數組
            } catch (PDOException $e) {
                $this->error = $e->getMessage();
                return false; // 操作失敗
            }
        }
    
        // 執行原生SQL語句
        public function execQuery($query, $params = array()) {
            try {
                // 創建預處理語句
                $stmt = $this->pdo->prepare($query);
        
                // 綁定參數
                foreach ($params as $key => $value) {
                    $stmt->bindValue($key, $value);
                }
        
                // 執行預處理語句
                $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 為示例作為示例代碼。

創建表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);
    
    // 數據
    $insertData = array(
        'title' => 'this is title',
        'content' => 'this is content',
    );
    
    // 執行
    $insertSQL = $db->add('test_table', $insertData);
    
    // 結果
    if ($insertSQL) {
        
        // 成功
        echo '插入成功,ID是:' . $insertSQL;
    } else {
        
        // 失敗
        echo '插入失敗,原因:' . $db->errorMsg();
    }
?>
update示例
<?php
    
    // 引入配置
    include 'Db.php';
    
    // 實例化
    $db = new DB_API($config);
    
    // 條件
    // 只支持=,不支持>,<,>=,<=之類的
    // 如需更復雜的條件請使用執行原生語句的方法
    $where = array(
        'id' => '1'
    );
    
    // 數據
    $updateData = array(
        'content' => 'content is updated'
    );
    
    // 執行
    $updatedSQL = $db->update('test_table', $where, $updateData);
    
    // 結果
    if ($updatedSQL) {
        
        // 成功
        echo '更新成功';
    } else {
        
        // 失敗
        echo '更新失敗,原因:' . $db->errorMsg();
    }

?>
delete示例
<?php
    
    // 引入配置
    include 'Db.php';
    
    // 實例化
    $db = new DB_API($config);
    
    // 條件
    $where = array(
        'id' => 4,
    );
    
    // 執行
    $deleteSQL = $db->delete('test_table', $where);
    
    // 結果
    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條件);
    // 如果查詢所有字段,使用'*'代替數組
    // $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']);
    
    // 根據以下條件
    // 查詢所有字段
    // $where = array(
    //     'id' => 3
    // );
    // $selectSQL = $db->select('test_table', '*', $where);
    
    // 根據以下條件
    // 查詢指定字段
    // $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);
    
    // 結果
    if ($selectSQL) {
        
        // 成功
        echo json_encode($selectSQL, JSON_UNESCAPED_UNICODE);
    } else {
        
        // 失敗
        echo '查詢失敗,原因:' . $db->errorMsg();
    }

?>
執行原生語句示例
<?php
    
    // 引入配置
    include 'Db.php';
    
    // 實例化
    $db = new DB_API($config);
    
    // SQL語句
    $query = "INSERT INTO test_table (title, content) VALUES (:title, :content)";
    
    // 數據綁定
    $params = array(
        ':title' => 'New Title By execQuery',
        ':content' => 'New Content By execQuery',
    );
    
    // 執行
    $querySQL = $db->execQuery($query, $params);
    
    // 結果
    if ($querySQL) {
        
        // 成功
        echo 'SQL執行成功!';
    } else {
        
        // 失敗
        echo 'SQL執行失敗,原因:' . $db->errorMsg();
    }

?>

作者

TANKING

user avatar iymxpc3k 頭像 layouwen 頭像 phytium_developers 頭像 jasinyip 頭像
4 位用戶收藏了這個故事!

發佈 評論

Some HTML is okay.