You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
103 lines
2.8 KiB
103 lines
2.8 KiB
<?php
|
|
|
|
require_once __ROOT__ . "/config.php";
|
|
require_once __ROOT__ . "/Log.php";
|
|
|
|
interface DoExcute
|
|
{
|
|
// 参数处理
|
|
function bind_param(mysqli_stmt $stmt, array $param);
|
|
|
|
// 执行结果处理
|
|
function doResult(mysqli_stmt $stmt);
|
|
}
|
|
|
|
class DbUtil
|
|
{
|
|
|
|
private static function getConn()
|
|
{
|
|
try {
|
|
$conn = new mysqli(db_config["servername"], db_config["username"], db_config["password"], db_config["dbname"]);
|
|
if ($conn->connect_error) {
|
|
error("数据库连接失败");
|
|
} else {
|
|
info("数据库连接成功");
|
|
}
|
|
return $conn;
|
|
} catch (Exception $e) {
|
|
error("数据库连接异常");
|
|
die("数据库连接异常");
|
|
}
|
|
}
|
|
|
|
private static function closeConn(mysqli $conn)
|
|
{
|
|
try {
|
|
if ($conn->close()) {
|
|
info("成功关闭数据库");
|
|
} else {
|
|
error("无法关闭数据库");
|
|
}
|
|
} catch (Exception $e) {
|
|
error("关闭数据库连接出现异常:" . $e);
|
|
}
|
|
}
|
|
|
|
// 插入数据
|
|
public static function modify($action, $sql, $types = "", ...$_)
|
|
{
|
|
|
|
try {// 创建连接
|
|
$conn = self::getConn();
|
|
$stmt = $conn->prepare("$sql");//创建一个预定义的对象 ?占位
|
|
if (!empty($types)) {
|
|
$stmt->bind_param($types, ...$_);// 参数绑定
|
|
}
|
|
$stmt->execute();// 执行sql
|
|
info($action . $stmt->affected_rows . "条数据");
|
|
$stmt->close();
|
|
info("执行sql.$sql.成功");
|
|
self::closeConn($conn);// 关闭连接
|
|
} catch (Exception $e) {
|
|
error($action . "数据异常" . $e);
|
|
}
|
|
}
|
|
|
|
// 插入数据
|
|
public static function insert($sql, $types = "", ...$_)
|
|
{
|
|
self::modify("插入", $sql, $types, ...$_);
|
|
}
|
|
|
|
// 更新数据
|
|
public static function update($sql, $types = "", ...$_)
|
|
{
|
|
self::modify("更新", $sql, $types, ...$_);
|
|
}
|
|
|
|
// 删除数据
|
|
public static function delete($sql, $types = "", ...$_)
|
|
{
|
|
self::modify("删除", $sql, $types, ...$_);
|
|
}
|
|
|
|
|
|
//查询数据
|
|
public static function query($sql, DoExcute $doExcute, array $param = array())
|
|
{
|
|
try {// 创建连接
|
|
$conn = self::getConn();
|
|
$stmt = $conn->prepare($sql);//创建一个预定义的对象 ?占位
|
|
$doExcute->bind_param($stmt, $param);
|
|
$stmt->execute();// 执行sql
|
|
$doExcute->doResult($stmt);
|
|
info("执行sql.$sql.成功");
|
|
$stmt->close();
|
|
// 关闭连接
|
|
self::closeConn($conn);
|
|
} catch (Exception $e) {
|
|
error("查询数据异常" . $e);
|
|
}
|
|
}
|
|
} |