博客 / 詳情

返回

php編寫的mysqli增刪改查數據庫操作類

這是一個php深度封裝的MySQLi數據庫操作類,支持插入、刪除、查詢和更新操作,並且使用數組進行參數傳遞,結合了預處理語句防止SQL注入。

類文件

Database.php

<?php
/**
 * mySqli數據庫操作類
 * 參數綁定防SQL注入
 * 作者:TANKING
 * 時間:2023-08-01
 **/

class Database
{
    private $host;
    private $username;
    private $password;
    private $database;
    private $conn;
    
    // 構造方法
    public function __construct($host, $username, $password, $database)
    {
        $this->host = $host;
        $this->username = $username;
        $this->password = $password;
        $this->database = $database;
        $this->connect();
    }
    
    // 連接數據庫
    public function connect()
    {
        $this->conn = new mysqli($this->host, $this->username, $this->password, $this->database);
        if ($this->conn->connect_error) {
            die("連接數據庫失敗:" . $this->conn->connect_error);
        }
    }
    
    // 斷開數據庫連接
    public function disconnect()
    {
        $this->conn->close();
    }
    
    // Query方法
    public function query($sql, $params = [])
    {
        $stmt = $this->conn->prepare($sql);

        if ($stmt === false) {
            throw new Exception("預處理失敗:" . $this->conn->error);
        }

        // 綁定參數
        if (!empty($params)) {
            $paramTypes = '';
            $bindParams = [];
            foreach ($params as $param) {
                if (is_int($param)) {
                    $paramTypes .= 'i'; // Integer
                } elseif (is_float($param)) {
                    $paramTypes .= 'd'; // Double
                } else {
                    $paramTypes .= 's'; // String
                }
                $bindParams[] = $param;
            }

            if (!empty($bindParams)) {
                $stmt->bind_param($paramTypes, ...$bindParams);
            }
        }

        $stmt->execute();
        $result = $stmt->get_result();

        if ($result === false) {
            throw new Exception("執行查詢失敗:" . $stmt->error);
        }

        $data = [];
        while ($row = $result->fetch_assoc()) {
            $data[] = $row;
        }

        $stmt->close();
        return $data;
    }
    
    // 查詢一條數據
    public function selectOne($table, $conditions = [], $params = [], $fields = ['*'])
    {
        $limit = 1;
        $result = $this->select($table, $conditions, $params, $limit, $fields);

        if ($result && count($result) > 0) {
            return $result[0];
        }

        return null;
    }
    
    // 查詢所有數據
    public function selectAll($table, $conditions = [], $params = [], $fields = ['*'])
    {
        return $this->select($table, $conditions, $params, null, $fields);
    }
    
    // 高級查詢
    public function select($table, $conditions = [], $params = [], $fields = ['*'], $limit = '', $orderBy = '')
    {
        $fields = implode(', ', $fields);
        $whereClause = '';

        if (!empty($conditions)) {
            $whereClause = ' WHERE ' . implode(' AND ', $conditions);
        }

        $orderByClause = '';
        if (!empty($orderBy)) {
            $orderByClause = ' ORDER BY ' . $orderBy;
        }

        $limitClause = '';
        if (!empty($limit)) {
            $limitClause = ' LIMIT ' . $limit;
        }

        $sql = "SELECT $fields FROM $table $whereClause $orderByClause $limitClause";
        $stmt = $this->conn->prepare($sql);

        if ($stmt === false) {
            die("預處理查詢失敗:" . $this->conn->error);
        }

        $types = '';
        $paramsToBind = [];

        foreach ($params as $param) {
            if (is_int($param)) {
                $types .= 'i'; // Integer
            } elseif (is_float($param)) {
                $types .= 'd'; // Double
            } else {
                $types .= 's'; // String
            }
            $paramsToBind[] = $param;
        }

        array_unshift($paramsToBind, $types);

        $bindResult = call_user_func_array([$stmt, 'bind_param'], $this->refValues($paramsToBind));
        if ($bindResult === false) {
            die("綁定參數失敗:" . $this->conn->error);
        }

        $stmt->execute();
        $result = $stmt->get_result();

        if ($result === false) {
            die("執行查詢失敗:" . $stmt->error);
        }

        $data = [];
        while ($row = $result->fetch_assoc()) {
            $data[] = $row;
        }

        $stmt->close();
        return $data;
    }
    
    // 插入數據
    public function insert($table, $data = [])
    {
        if (empty($data)) {
            die("插入數據失敗:數據為空");
        }

        $fields = implode(', ', array_keys($data));
        $placeholders = implode(', ', array_fill(0, count($data), '?'));

        $sql = "INSERT INTO $table ($fields) VALUES ($placeholders)";
        $params = array_values($data);

        $stmt = $this->conn->prepare($sql);

        if ($stmt === false) {
            die("預處理失敗:" . $this->conn->error);
        }

        $types = '';
        $paramsToBind = [];

        foreach ($params as $param) {
            if (is_int($param)) {
                $types .= 'i'; // Integer
            } elseif (is_float($param)) {
                $types .= 'd'; // Double
            } else {
                $types .= 's'; // String
            }
            $paramsToBind[] = $param;
        }

        array_unshift($paramsToBind, $types);

        $bindResult = call_user_func_array([$stmt, 'bind_param'], $this->refValues($paramsToBind));
        if ($bindResult === false) {
            die("綁定參數失敗:" . $this->conn->error);
        }
        
        // 插入結果
        $result = $stmt->execute();
        
        // 斷開數據庫連接
        $stmt->close();
        
        // 返回結果
        return $result;
    }
    
    // 更新數據
    public function update($table, $data = [], $conditions = [], $params = [])
    {
        if (empty($data)) {
            die("更新數據失敗:更新數據為空");
        }

        $updateFields = implode(' = ?, ', array_keys($data)) . ' = ?';
        $whereClause = '';

        if (!empty($conditions)) {
            $whereClause = ' WHERE ' . implode(' AND ', $conditions);
        }

        $sql = "UPDATE $table SET $updateFields $whereClause";
        $updateParams = array_merge(array_values($data), $params);

        $stmt = $this->conn->prepare($sql);

        if ($stmt === false) {
            die("預處理失敗:" . $this->conn->error);
        }

        $types = '';
        $paramsToBind = [];

        foreach ($updateParams as $param) {
            if (is_int($param)) {
                $types .= 'i'; // Integer
            } elseif (is_float($param)) {
                $types .= 'd'; // Double
            } else {
                $types .= 's'; // String
            }
            $paramsToBind[] = $param;
        }

        array_unshift($paramsToBind, $types);

        $bindResult = call_user_func_array([$stmt, 'bind_param'], $this->refValues($paramsToBind));
        if ($bindResult === false) {
            die("綁定參數失敗:" . $this->conn->error);
        }

        $result = $stmt->execute();

        $stmt->close();

        return $result;
    }
    
    // 刪除數據
    public function delete($table, $conditions = [], $params = [])
    {
        if (empty($conditions)) {
            die("刪除數據失敗:刪除條件為空");
        }

        $whereClause = ' WHERE ' . implode(' AND ', $conditions);
        $sql = "DELETE FROM $table $whereClause";

        $stmt = $this->conn->prepare($sql);

        if ($stmt === false) {
            die("預處理查詢失敗:" . $this->conn->error);
        }

        $types = '';
        $paramsToBind = [];

        foreach ($params as $param) {
            if (is_int($param)) {
                $types .= 'i'; // Integer
            } elseif (is_float($param)) {
                $types .= 'd'; // Double
            } else {
                $types .= 's'; // String
            }
            $paramsToBind[] = $param;
        }

        array_unshift($paramsToBind, $types);

        $bindResult = call_user_func_array([$stmt, 'bind_param'], $this->refValues($paramsToBind));
        if ($bindResult === false) {
            die("綁定參數失敗:" . $this->conn->error);
        }

        $result = $stmt->execute();

        $stmt->close();

        return $result;
    }
    
    // 執行原生語句
    public function querySQL($sql)
    {
        $result = $this->conn->query($sql);

        if ($result === false) {
            die("執行原生失敗:" . $this->conn->error);
        }

        return $result;
    }
    
    // 數據綁定
    private function refValues($arr)
    {
        if (strnatcmp(phpversion(), '5.3') >= 0) // Reference is required for PHP 5.3+
        {
            $refs = array();
            foreach ($arr as $key => $value) {
                $refs[$key] = &$arr[$key];
            }
            return $refs;
        }
        return $arr;
    }
}

?>

配置文件

Db.php

<?php

// 數據庫配置文件
$config = array(
    'db_host' => 'xxx',
    'db_user' => 'xxx',
    'db_pass' => 'xxx',
    'db_name' => 'xxx'
);

// 數據庫操作類
include 'Database.php';

?>

使用示例

插入數據
insert.php
<?php

// 引入配置文件
require_once 'Db.php';

// 實例化Database類並連接數據庫
$db = new Database($config['db_host'], $config['db_user'], $config['db_pass'], $config['db_name']);

// 插入數據
$insertParams = array(
    'stu_name' => '蔡徐坤',
    'stu_sex' => '男',
    'stu_from' => '廣州',
    'stu_grade' => '一年級',
    'stu_age' => 30,
);

// 執行
$insertData = $db->insert('students', $insertParams);

// 執行結果
if($insertData){
    
    echo '插入成功!'; 
}else{
    
    echo '插入失敗!'.$insertData;
}

// 關閉連接
$db->disconnect();

?>
更新數據
update.php
<?php

// 引入配置文件
require_once 'Db.php';

// 實例化Database類並連接數據庫
$db = new Database($config['db_host'], $config['db_user'], $config['db_pass'], $config['db_name']);

// 被更新的數據
$updateData = array(
    'stu_name' => '吳亦凡666',
    'stu_age' => 35
);

// 綁定參數
$updateCondition = array('id = ?');
$updateParams = array(1);

// 執行
$updateResult = $db->update('students', $updateData, $updateCondition, $updateParams);

// 執行結果
if($updateResult){
    
    echo '更新成功!'; 
}else{
    
    echo '更新失敗!'.$updateResult;
}

// 關閉連接
$db->disconnect();

?>
刪除數據
delete.php
<?php

// 引入配置文件
require_once 'Db.php';

// 實例化Database類並連接數據庫
$db = new Database($config['db_host'], $config['db_user'], $config['db_pass'], $config['db_name']);

// 綁定參數
$conditions = array('id = ?');
$params = array(2);

// 執行
$deleteResult = $db->delete('students', $conditions, $params);

if ($deleteResult) {
    
    echo "刪除成功!";
} else {
    
    echo "刪除失敗。";
}

// 關閉連接
$db->disconnect();

?>
查詢一條數據
selectOne.php
<?php

// 引入配置文件
require_once 'Db.php';

// 實例化Database類並連接數據庫
$db = new Database($config['db_host'], $config['db_user'], $config['db_pass'], $config['db_name']);

// 準備查詢的條件和字段
$conditions = array('id = ?');
$params = array(1);
$fields = array('id', 'stu_name', 'stu_age', 'stu_from');

// 執行
$selectedData = $db->selectOne('students', $conditions, $params, $fields);

// 執行結果
if ($selectedData) {
    
    echo "查詢到一條數據:<br>";
    echo "ID: " . $selectedData['id'] . "<br>";
    echo "stu_name: " . $selectedData['stu_name'] . "<br>";
    echo "stu_age: " . $selectedData['stu_age'] . "<br>";
    echo "stu_from: " . $selectedData['stu_from'] . "<br>";
} else {
    
    echo "未查詢到數據。";
}

// 關閉連接
$db->disconnect();

?>
查詢所有數據
selectAll.php
<?php

// 引入配置文件
require_once 'Db.php';

// 實例化Database類並連接數據庫
$db = new Database($config['db_host'], $config['db_user'], $config['db_pass'], $config['db_name']);

// 準備查詢的條件和字段
$conditions = array('stu_sex = ?');
$params = array('男');
$fields = array('id', 'stu_name', 'stu_age', 'stu_from');

// 執行
$selectedData = $db->selectAll('students', $conditions, $params, $fields);

// 執行結果
if ($selectedData) {
    
    echo "查詢到的所有數據:<br>";
    foreach ($selectedData as $data) {
        echo "ID: " . $data['id'] . "<br>";
        echo "stu_name: " . $data['stu_name'] . "<br>";
        echo "stu_age: " . $data['stu_age'] . "<br>";
        echo "stu_from: " . $data['stu_from'] . "<br>";
        echo "<br>";
    }
} else {
    
    echo "未查詢到數據。";
}

// 關閉連接
$db->disconnect();

?>
高級查詢
select.php
<?php

// 引入配置文件
require_once 'Db.php';

// 實例化Database類並連接數據庫
$db = new Database($config['db_host'], $config['db_user'], $config['db_pass'], $config['db_name']);

// 準備查詢的條件和字段
$conditions = array('stu_age > ?');
$params = array(25);
$fields = array('id', 'stu_name', 'stu_age', 'stu_from');
$limit = 3; // 查詢限制條數
$orderBy = 'id DESC'; // 排序方式

// 執行
$selectedData = $db->select('students', $conditions, $params, $fields, $limit, $orderBy);

// 執行結果
if ($selectedData) {
    
    echo "查詢到的數據:<br>";
    foreach ($selectedData as $data) {
        echo "ID: " . $data['id'] . "<br>";
        echo "stu_name: " . $data['stu_name'] . "<br>";
        echo "stu_age: " . $data['stu_age'] . "<br>";
        echo "stu_from: " . $data['stu_from'] . "<br>";
        echo "<br>";
    }
} else {
    
    echo "未查詢到數據。";
}

// 關閉連接
$db->disconnect();

?>
執行原生語句
querySQL.php
<?php

// 引入配置文件
require_once 'Db.php';

// 實例化Database類並連接數據庫
$db = new Database($config['db_host'], $config['db_user'], $config['db_pass'], $config['db_name']);

// 執行
$sql = "SELECT * FROM students WHERE stu_age > 25";
$result = $db->querySQL($sql);

// 執行結果
if ($result->num_rows > 0) {
    
    echo "查詢到的數據:<br>";
    while ($data = $result->fetch_assoc()) {
        echo "ID: " . $data['id'] . "<br>";
        echo "stu_name: " . $data['stu_name'] . "<br>";
        echo "stu_age: " . $data['stu_age'] . "<br>";
        echo "stu_from: " . $data['stu_from'] . "<br>";
        echo "<br>";
    }
} else {
    
    echo "未查詢到數據。";
}

// 關閉連接
$db->disconnect();

?>

作者

TANKING

user avatar tingtr 頭像 wodingshangniliao 頭像
2 位用戶收藏了這個故事!

發佈 評論

Some HTML is okay.