表單隱藏欄位 <input type="hidden" name="id" value="<?=$id??''?>">,後端依 id 存在與否決定 INSERT 或 UPDATE。
<?php
function saveArticle(array $input, array $files): array
{
// 1. 驗證必填
if (empty($input['title']) || empty($input['content'])) {
return ['success' => false, 'msg' => '標題與內容不可為空'];
}
// 2. 處理附件上傳
$attachment = null;
if (!empty($files['attachment']['name'])) {
$upload = uploadFile($files['attachment'], ['pdf','doc','docx','jpg','png'], 5 * 1024 * 1024);
if (!$upload['success']) return $upload;
$attachment = $upload['path'];
}
// 3. 準備資料
$data = [
'title' => $input['title'],
'content' => $input['content'],
'updated_at' => date('Y-m-d H:i:s'),
];
if ($attachment) {
$data['attachment_path'] = $attachment;
}
// 4. 新增或更新
$id = $input['id'] ?? 0;
if ($id > 0) {
// 編輯:若無新附件,保留原附件
$stmt = $pdo->prepare('UPDATE articles SET title=?, content=?, attachment_path=COALESCE(?, attachment_path), updated_at=? WHERE id=?');
$stmt->execute([$data['title'], $data['content'], $attachment, $data['updated_at'], $id]);
$msg = '更新成功';
} else {
$data['created_at'] = $data['updated_at'];
$stmt = $pdo->prepare('INSERT INTO articles (title, content, attachment_path, created_at, updated_at) VALUES (?,?,?,?,?)');
$stmt->execute([$data['title'], $data['content'], $attachment, $data['created_at'], $data['updated_at']]);
$id = $pdo->lastInsertId();
$msg = '新增成功';
}
return ['success' => true, 'msg' => $msg, 'id' => $id];
}
?>
<form method="post" enctype="multipart/form-data">
<input type="hidden" name="id" value="<?= $article['id'] ?? '' ?>">
<label>標題</label>
<input name="title" value="<?= htmlspecialchars($article['title'] ?? '') ?>" required>
<label>內容</label>
<textarea name="content" required><?= htmlspecialchars($article['content'] ?? '') ?></textarea>
<label>附件</label>
<?php if (!empty($article['attachment_path'])): ?>
現有:<a href="<?= $article['attachment_path'] ?>" target="_blank">下載</a>
<label><input type="checkbox" name="remove_attachment"> 移除附件</label>
<?php endif; ?>
<input type="file" name="attachment" accept=".pdf,.doc,.docx,.jpg,.png">
<button type="submit">儲存</button>
</form>
COALESCE(?, attachment_path),新檔案才更新,否則保持原值。remove_attachment=1 時將欄位設為 NULL 並刪除實體檔案。<input type="hidden" name="_token" value="<?= csrf_token() ?>">。