php技巧

关注公众号 jb51net

关闭
首页 > 网络编程 > PHP编程 > php技巧 > php mysqli增删改查

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

作者:TANKING

这篇文章主要为大家介绍了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();
?>

以上就是php编写的mysqli增删改查数据库操作类示例的详细内容,更多关于php mysqli增删改查的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文