prepare("SELECT * FROM settings LIMIT 1");
$stmt->execute();
$record = $stmt->get_result()->fetch_assoc();
$stmt->close();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$id = intval($_POST['id']);
$cname = trim($_POST['cname']);
$description = trim($_POST['description']);
$keywords = trim($_POST['keywords']);
// 1) 默认沿用旧 logo(关键修正点)
$logoPathForDB = $record['logo'] ?? '';
// 2) 如果上传了新文件才尝试覆盖
if (!empty($_FILES['logo']['name']) && $_FILES['logo']['error'] === UPLOAD_ERR_OK) {
// 展示用的URL路径(存数据库用于
![]()
)
$uploadUrlDir = "/uploads/"; // 建议用网站根路径开头,方便前端显示
// 真实文件系统路径(用于保存/删除文件)
$uploadFsDir = $_SERVER['DOCUMENT_ROOT'] . $uploadUrlDir;
if (!is_dir($uploadFsDir)) mkdir($uploadFsDir, 0777, true);
$ext = strtolower(pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION));
$safe = preg_replace('/[^a-zA-Z0-9_\-\.]/', '_', pathinfo($_FILES['logo']['name'], PATHINFO_FILENAME));
$newName = date("Ymd_His") . "_" . $safe . ($ext ? "." . $ext : "");
$targetFs = $uploadFsDir . $newName; // 磁盘路径
$targetUrl = $uploadUrlDir . $newName; // 存DB的URL
// 可选:简单的MIME检查
// $finfo = finfo_open(FILEINFO_MIME_TYPE);
// $mime = finfo_file($finfo, $_FILES['logo']['tmp_name']);
// if (!in_array($mime, ['image/png','image/jpeg','image/gif','image/webp'])) { ... }
if (move_uploaded_file($_FILES['logo']['tmp_name'], $targetFs)) {
// 删除旧文件(只有当旧记录是站内上传的文件时才尝试删除)
if (!empty($record['logo'])) {
$oldUrl = $record['logo']; // e.g. "/uploads/xxx.png"
$oldFs = $_SERVER['DOCUMENT_ROOT'] . $oldUrl;
if (is_file($oldFs)) { @unlink($oldFs); }
}
// 覆盖为新文件(只在成功上传时)
$logoPathForDB = $targetUrl;
}
}
// 3) 更新数据库(logo 用 $logoPathForDB,不会被清空)
$sql = "UPDATE settings SET logo=?, cname=?, description=?, keywords=? WHERE id=?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ssssi", $logoPathForDB, $cname, $description, $keywords, $id);
if ($stmt->execute()) {
echo "
✅ 数据更新成功
";
// 可选:刷新 $record,避免页面仍显示旧图
$stmt->close();
$stmt = $conn->prepare("SELECT * FROM settings WHERE id=? LIMIT 1");
$stmt->bind_param("i", $id);
$stmt->execute();
$record = $stmt->get_result()->fetch_assoc();
} else {
echo "
❌ 更新失败:" . htmlspecialchars($stmt->error) . "
";
}
$stmt->close();
}
?>
表里没有数据,请先插入一条。