萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 單一表單處理新增與編輯:統一邏輯、檔案上傳與資料保護

核心概念:以 ID 區分新增/編輯

表單隱藏欄位 <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>

關鍵細節

  • 編輯時保留原附件:SQL 使用 COALESCE(?, attachment_path),新檔案才更新,否則保持原值。
  • 移除附件勾選框:後端收到 remove_attachment=1 時將欄位設為 NULL 並刪除實體檔案。
  • CSRF 保護:表單加入 <input type="hidden" name="_token" value="<?= csrf_token() ?>">。
  • 權限檢查:編輯前驗證使用者是否擁有該筆資料編輯權限。
copyright © 萬盛學電腦網 all rights reserved