prepare("SELECT * FROM sectiona WHERE type='item' AND section_key=? ORDER BY sort_order ASC, id ASC LIMIT 3");
$stmt->bind_param("s", $section_key);
$stmt->execute();
$res = $stmt->get_result();
$items = [];
while ($row = $res->fetch_assoc()) { $items[] = $row; }
$stmt->close();
if (empty($items)) {
echo "
分组 ".htmlspecialchars($section_key)." 下没有 item。请先插入 3 条 type='item' 的记录。
";
exit;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$ids = $_POST['id'] ?? [];
$titles = $_POST['title_text'] ?? [];
$contents = $_POST['content_text'] ?? [];
$sort_orders = $_POST['sort_order'] ?? [];
$actives = $_POST['is_active'] ?? []; // is_active[i] 存在即启用
// id => row 的映射,便于拿旧图
$byId = [];
foreach ($items as $it) { $byId[$it['id']] = $it; }
// 上传目录
$uploadUrlDir = "/uploads/core_values/";
$docRoot = rtrim($_SERVER['DOCUMENT_ROOT'], '/');
$uploadFsDir = $docRoot . $uploadUrlDir;
if (!is_dir($uploadFsDir)) { mkdir($uploadFsDir, 0777, true); }
for ($i = 0; $i < count($ids); $i++) {
$id = intval($ids[$i]);
if (!isset($byId[$id])) continue;
$title_text = trim($titles[$i] ?? '');
$content_text = trim($contents[$i] ?? '');
$sort_order = intval($sort_orders[$i] ?? 0);
$is_active = isset($actives[$i]) ? 1 : 0;
// 默认保留旧图
$imagePathForDB = $byId[$id]['image_path'] ?? '';
// 对应 file input:image_0 / image_1 / image_2
$fileKey = "image_$i";
if (!empty($_FILES[$fileKey]['name']) && $_FILES[$fileKey]['error'] === UPLOAD_ERR_OK) {
$ext = strtolower(pathinfo($_FILES[$fileKey]['name'], PATHINFO_EXTENSION));
$safe = preg_replace('/[^a-zA-Z0-9_\-\.]/', '_', pathinfo($_FILES[$fileKey]['name'], PATHINFO_FILENAME));
$newName = date("Ymd_His") . "_" . $safe . ($ext ? "." . $ext : "");
$targetFs = $uploadFsDir . $newName;
$targetUrl = $uploadUrlDir . $newName;
if (is_uploaded_file($_FILES[$fileKey]['tmp_name']) && move_uploaded_file($_FILES[$fileKey]['tmp_name'], $targetFs)) {
// 删旧图(站内)
if (!empty($byId[$id]['image_path'])) {
$oldFs = $docRoot . $byId[$id]['image_path'];
if (is_file($oldFs)) { @unlink($oldFs); }
}
$imagePathForDB = $targetUrl;
} else {
echo "
ID {$id} 图片上传失败(保持旧图)。
";
}
}
// 更新
$sql = "UPDATE sectiona
SET title_text=?, content_text=?, image_path=?, sort_order=?, is_active=?
WHERE id=? AND type='item' AND section_key=?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("sssiiis", $title_text, $content_text, $imagePathForDB, $sort_order, $is_active, $id, $section_key);
if (!$stmt->execute()) {
echo "
❌ 更新失败(ID {$id}):".htmlspecialchars($stmt->error)."
";
}
$stmt->close();
}
// 重新读取最新
$stmt = $conn->prepare("SELECT * FROM sectiona WHERE type='item' AND section_key=? ORDER BY sort_order ASC, id ASC LIMIT 3");
$stmt->bind_param("s", $section_key);
$stmt->execute();
$res = $stmt->get_result();
$items = [];
while ($row = $res->fetch_assoc()) { $items[] = $row; }
$stmt->close();
echo "
✅ 批量更新完成
";
}
?>