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

 更新时间:2023年08月02日 11:15:34   作者: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增删改查的资料请关注脚本之家其它相关文章!

相关文章

  • php 安全过滤函数代码

    php 安全过滤函数代码

    php 安全过滤函数代码,防止用户恶意输入内容。
    2011-05-05
  • php实现的mysqldb读写分离操作类示例

    php实现的mysqldb读写分离操作类示例

    这篇文章主要介绍了php实现的mysqldb读写分离操作类,结合实例形式分析了php针对数据库的读写分离操作实现技巧,并给出了该封装类的具体使用方法,需要的朋友可以参考下
    2017-02-02
  • PHP中header用法小结

    PHP中header用法小结

    这篇文章主要介绍了PHP中header用法,总结分析了header函数的基本功能与相应的使用技巧,需要的朋友可以参考下
    2016-05-05
  • php 判断页面或图片是否经过gzip压缩的方法

    php 判断页面或图片是否经过gzip压缩的方法

    下面小编就为大家带来一篇php 判断页面或图片是否经过gzip压缩的方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-04-04
  • PHP编程获取各个时间段具体时间的方法

    PHP编程获取各个时间段具体时间的方法

    这篇文章主要介绍了PHP编程获取各个时间段具体时间的方法,结合实例形式分析了基于date与strtotime函数进行日期时间运算的相关操作技巧,需要的朋友可以参考下
    2017-05-05
  • 六酷社区论坛HOME页清新格调免费版 下载

    六酷社区论坛HOME页清新格调免费版 下载

    六酷社区论坛HOME页清新格调免费版 下载...
    2007-03-03
  • PHP高精确度运算BC函数库实例详解

    PHP高精确度运算BC函数库实例详解

    这篇文章主要介绍了PHP高精确度运算BC函数库,结合实例形式分析了BC函数库中bccomp、bcadd、bcsub、bcmod、bcdiv、bcmul等函数的功能以及高精度数学运算使用方法,需要的朋友可以参考下
    2017-08-08
  • php中数据库连接方式pdo和mysqli对比分析

    php中数据库连接方式pdo和mysqli对比分析

    这篇文章主要介绍了php中数据库连接方式pdo和mysqli从各个方面进行了对比分析,十分全面,这里推荐给大家,有需要的小伙伴来参考下。
    2015-02-02
  • PHP中引用类型和值类型功能与用法示例

    PHP中引用类型和值类型功能与用法示例

    这篇文章主要介绍了PHP中引用类型和值类型功能与用法,简单分析了php引用类型和值类型的概念、功能、使用方法及相关操作注意事项,需要的朋友可以参考下
    2019-02-02
  • PHP把MSSQL数据导入到MYSQL的方法

    PHP把MSSQL数据导入到MYSQL的方法

    这篇文章主要介绍了PHP把MSSQL数据导入到MYSQL的方法,分别列举了两个实例实现将MSSQL数据导入到MYSQL的功能,是非常实用的技巧,具有一定的参考借鉴价值,需要的朋友可以参考下
    2014-12-12

最新评论