refactor(数据库配置): 将数据库配置移至外部文件并添加错误处理
重构数据库连接配置,从独立文件引入配置并添加配置检查 确保配置变量存在时才会继续执行,提高代码健壮性
This commit is contained in:
+15
-5
@@ -2,11 +2,21 @@
|
|||||||
header('Content-Type: application/json; charset=utf-8');
|
header('Content-Type: application/json; charset=utf-8');
|
||||||
header('Cache-Control: no-cache, must-revalidate');
|
header('Cache-Control: no-cache, must-revalidate');
|
||||||
|
|
||||||
// 数据库连接配置
|
// 引入根目录的数据库配置文件
|
||||||
$host = 'localhost';
|
require_once __DIR__ . '/config.php';
|
||||||
$dbname = 'carwash_booking';
|
|
||||||
$username = 'root';
|
// 确保配置变量存在
|
||||||
$password = '';
|
if (!isset($host) || !isset($username) || !isset($password) || !isset($database)) {
|
||||||
|
http_response_code(500);
|
||||||
|
echo json_encode([
|
||||||
|
'error' => '配置文件加载失败',
|
||||||
|
'message' => '无法读取数据库配置信息'
|
||||||
|
], JSON_UNESCAPED_UNICODE);
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 配置变量重命名,确保兼容性
|
||||||
|
$dbname = $database;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
$pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
|
$pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
|
||||||
|
|||||||
Reference in New Issue
Block a user