php编写的mysqli增删改查数据库操作类

这是一个php深度封装的MySQLi数据库操作类,支持插入、删除、查询和更新操作,并且使用数组进行参数传递,结合了预处理语句防止SQL注入。

类文件

Database.php

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

 'xxx',
    'db_user' => 'xxx',
    'db_pass' => 'xxx',
    'db_name' => 'xxx'
);

// 数据库操作类
include 'Database.php';

?>

使用示例

插入数据
insert.php
 '蔡徐坤',
    'stu_sex' => '男',
    'stu_from' => '广州',
    'stu_grade' => '一年级',
    'stu_age' => 30,
);

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

// 执行结果
if($insertData){
    
    echo '插入成功!'; 
}else{
    
    echo '插入失败!'.$insertData;
}

// 关闭连接
$db->disconnect();

?>
更新数据
update.php
 '吴亦凡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
delete('students', $conditions, $params);

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

// 关闭连接
$db->disconnect();

?>
查询一条数据
selectOne.php
selectOne('students', $conditions, $params, $fields);

// 执行结果
if ($selectedData) {
    
    echo "查询到一条数据:
"; echo "ID: " . $selectedData['id'] . "
"; echo "stu_name: " . $selectedData['stu_name'] . "
"; echo "stu_age: " . $selectedData['stu_age'] . "
"; echo "stu_from: " . $selectedData['stu_from'] . "
"; } else { echo "未查询到数据。"; } // 关闭连接 $db->disconnect(); ?>
查询所有数据
selectAll.php
selectAll('students', $conditions, $params, $fields);

// 执行结果
if ($selectedData) {
    
    echo "查询到的所有数据:
"; foreach ($selectedData as $data) { echo "ID: " . $data['id'] . "
"; echo "stu_name: " . $data['stu_name'] . "
"; echo "stu_age: " . $data['stu_age'] . "
"; echo "stu_from: " . $data['stu_from'] . "
"; echo "
"; } } else { echo "未查询到数据。"; } // 关闭连接 $db->disconnect(); ?>
高级查询
select.php
 ?');
$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 "查询到的数据:
"; foreach ($selectedData as $data) { echo "ID: " . $data['id'] . "
"; echo "stu_name: " . $data['stu_name'] . "
"; echo "stu_age: " . $data['stu_age'] . "
"; echo "stu_from: " . $data['stu_from'] . "
"; echo "
"; } } else { echo "未查询到数据。"; } // 关闭连接 $db->disconnect(); ?>
执行原生语句
querySQL.php
 25";
$result = $db->querySQL($sql);

// 执行结果
if ($result->num_rows > 0) {
    
    echo "查询到的数据:
"; while ($data = $result->fetch_assoc()) { echo "ID: " . $data['id'] . "
"; echo "stu_name: " . $data['stu_name'] . "
"; echo "stu_age: " . $data['stu_age'] . "
"; echo "stu_from: " . $data['stu_from'] . "
"; echo "
"; } } else { echo "未查询到数据。"; } // 关闭连接 $db->disconnect(); ?>

作者

TANKING

你可能感兴趣的:(php编写的mysqli增删改查数据库操作类)