公告
  
重要通知:网站网络变更中可能出现站点图片无法加载的问题,点击此处可解决!
更多资讯可访问:点击查看消息详情!

朕已阅

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

admin 千秋月 关注 管理组 论坛神话
发表于程序代码版块 技术杂文
类文件

Database.php

<?php
/**
 * DEMO
 **/

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();

?>

本文章最后由 admin2023-10-09 18:28 编辑
评论列表 评论
发布评论

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



点击进入免费吃瓜群!吃大瓜! 广告位支持代码、文字、图片展示 Image


免责声明
本站资源,均来自网络,版权归原作者,所有资源和文章仅限用于学习和研究目的 。 不得用于商业或非法用途,否则,一切责任由该用户承担 !

请求资源或报告无效资源,请点击[反馈中心]


侵权删除请致信 E-Mail:chengfengad@gmail.com
已有0次打赏
(0) 分享
分享
取消