初始化

This commit is contained in:
2026-08-08 18:28:49 +08:00
parent 9bef4420e0
commit f082037a6e
854 changed files with 217171 additions and 11 deletions
+40
View File
@@ -0,0 +1,40 @@
<?php
namespace core\db;
use PDO;
use PDOException;
/**
* 数据库操作类
*/
class Db
{
private static $pdo = null;
public static function pdo()
{
if (self::$pdo !== null) {
return self::$pdo;
}
try {
$dsn = sprintf('mysql:host=%s;dbname=%s;charset=utf8mb4', DB_HOST, DB_NAME);
$option = array(
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
// 强制开启查询缓冲:避免「2014 Cannot execute queries while other
// unbuffered queries are active」。该连接在多处被复用(单例),
// 若不缓冲,前一条语句的结果集未取完就会阻塞后续查询。
PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true,
);
$pdo = new PDO($dsn, DB_USER, DB_PASS, $option);
// 部分环境在构造选项里设置不生效,再显式 setAttribute 兜底
$pdo->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
return self::$pdo = $pdo;
} catch (PDOException $e) {
error_log('DB connection error: ' . $e->getMessage());
exit('数据库连接失败,请联系管理员');
}
}
}
+56
View File
@@ -0,0 +1,56 @@
<?php
namespace core\db;
/**
* SQL 辅助类
*/
class Sql
{
// 构建 INSERT 语句
public static function insert($table, $data)
{
$fields = implode(', ', array_keys($data));
$placeholders = ':' . implode(', :', array_keys($data));
return 'INSERT INTO ' . $table . ' (' . $fields . ') VALUES (' . $placeholders . ')';
}
// 构建 UPDATE 语句
public static function update($table, $data, $where = '')
{
$set = array();
foreach ($data as $key => $value) {
$set[] = $key . ' = :' . $key;
}
$sql = 'UPDATE ' . $table . ' SET ' . implode(', ', $set);
if ($where) {
$sql .= ' WHERE ' . $where;
}
return $sql;
}
// 构建 SELECT 语句
public static function select($table, $fields = '*', $where = '', $order = '', $limit = '')
{
$sql = 'SELECT ' . $fields . ' FROM ' . $table;
if ($where) {
$sql .= ' WHERE ' . $where;
}
if ($order) {
$sql .= ' ORDER BY ' . $order;
}
if ($limit) {
$sql .= ' LIMIT ' . $limit;
}
return $sql;
}
// 构建 DELETE 语句
public static function delete($table, $where = '')
{
$sql = 'DELETE FROM ' . $table;
if ($where) {
$sql .= ' WHERE ' . $where;
}
return $sql;
}
}