---
title: "DB-Edit MySQL Record（讀取資料回填 HTML 表單再寫回）(tc)"
description: 本文說明如何用 PHP 編輯 MySQL 記錄：先用 id 讀取一筆資料、回填（populate）到 HTML 表單，用戶修改後再以 UPDATE 寫回。涵蓋單行文字、多行文字、核取方塊（checkbox）與選項按鈕（radio）四種欄位的回填方式。
url: "https://aaronchan.com/zh/kb/db-edit-mysql-record/"
updated: "2026-09-18"
category: "Code-php+MySQL (tc)"
---

# DB-Edit MySQL Record（讀取資料回填 HTML 表單再寫回）(tc)

本文說明如何用 PHP 編輯 MySQL 記錄：先用 `id` 讀取一筆資料、回填（populate）到 HTML 表單，用戶修改後再以 `UPDATE` 寫回。涵蓋單行文字、多行文字、核取方塊（checkbox）與選項按鈕（radio）四種欄位的回填方式。

## 🧭 工作流程概覽

「編輯記錄」的核心流程只有三步，任何一個欄位類型都遵循同一模式：

| 步驟 | 動作 | 說明 |
| --- | --- | --- |
| 1️⃣ | **讀取（Retrieve）** | 用 `id` 查詢資料庫，把該筆記錄取出來 |
| 2️⃣ | **回填（Populate）** | 把取出的值填進 HTML 表單對應欄位 |
| 3️⃣ | **寫回（Write back）** | 表單送出後，用 `UPDATE` 把新值存回資料庫 |

---

## 🗄️ 資料表結構

建立 `users` 資料表，四個欄位分別對應四種表單輸入類型：

 Copy

```
CREATE TABLE users (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(100) NOT NULL,          -- single-line text
  bio TEXT,                            -- multi-line text
  is_active TINYINT(1) DEFAULT 0,      -- checkbox (0/1)
  gender ENUM('male','female','other') -- radio button
);
```

---

## 🔌 資料庫連線（db.php）

 Copy

```
<?php
// db.php — reusable PDO connection
function getPDO(): PDO {
    $host = '127.0.0.1';
    $db   = 'mydb';
    $user = 'dbuser';
    $pass = 'secret';
    $dsn  = "mysql:host=$host;dbname=$db;charset=utf8mb4";
    return new PDO($dsn, $user, $pass, [
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]);
}

// escape helper — always escape before output to HTML
function e(?string $v): string {
    return htmlspecialchars($v ?? '', ENT_QUOTES, 'UTF-8');
}
```

---

## 📖 讀取 + 回填表單（edit.php）

 Copy

```
<?php
require 'db.php';

// Step 1: read & validate the id
$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if (!$id) { http_response_code(400); exit('Invalid record ID'); }

$stmt = getPDO()->prepare('SELECT * FROM users WHERE id = :id');
$stmt->execute(['id' => $id]);
$u = $stmt->fetch();

if (!$u) { http_response_code(404); exit('Record not found'); }
?>
<form method="post" action="save.php">
  <input type="hidden" name="id" value="<?= $u['id'] ?>">

  <!-- 1. single-line text field: value attribute -->
  <label>Name
    <input type="text" name="name" value="<?= e($u['name']) ?>">
  </label>

  <!-- 2. multi-line text field: content goes between the tags, no value attribute -->
  <label>Bio
    <textarea name="bio" rows="5" cols="40"><?= e($u['bio']) ?></textarea>
  </label>

  <!-- 3. checkbox: checked attribute -->
  <label>Active
    <input type="checkbox" name="is_active" value="1"
      <?= $u['is_active'] ? 'checked' : '' ?>>
  </label>

  <!-- 4. radio button: compare the value, add checked when it matches -->
  <fieldset>Gender
    <label><input type="radio" name="gender" value="male"
      <?= $u['gender'] === 'male' ? 'checked' : '' ?>> Male</label>
    <label><input type="radio" name="gender" value="female"
      <?= $u['gender'] === 'female' ? 'checked' : '' ?>> Female</label>
    <label><input type="radio" name="gender" value="other"
      <?= $u['gender'] === 'other' ? 'checked' : '' ?>> Other</label>
  </fieldset>

  <button type="submit">Save</button>
</form>
```

---

## 💾 寫回資料庫（save.php）

 Copy

```
<?php
require 'db.php';

$id   = filter_input(INPUT_POST, 'id', FILTER_VALIDATE_INT);
$name = trim($_POST['name'] ?? '');
$bio  = trim($_POST['bio'] ?? '');

// an unchecked checkbox is not submitted — use isset() to detect it
$is_active = isset($_POST['is_active']) ? 1 : 0;
$gender    = $_POST['gender'] ?? null;

if (!$id || $name === '') { http_response_code(400); exit('Invalid input'); }

$sql = "UPDATE users
        SET name = :name,
            bio = :bio,
            is_active = :is_active,
            gender = :gender
        WHERE id = :id";

$stmt = getPDO()->prepare($sql);
$stmt->execute([
    'name'      => $name,
    'bio'       => $bio,
    'is_active' => $is_active,
    'gender'    => $gender,
    'id'        => $id,
]);

header('Location: edit.php?id=' . $id);
exit;
```

---

## 🧩 四種欄位回填方式對照表

| 欄位類型 | HTML Element | 回填方式 | 關鍵屬性 |
| --- | --- | --- | --- |
| 單行文字 | `<input type="text">` | `value` 屬性 | `value="..."` |
| 多行文字 | `<textarea>` | 標籤之間的內容 | 沒有 `value` 屬性 |
| 核取方塊 | `<input type="checkbox">` | `checked` 屬性 | 值為 1/0 |
| 選項按鈕 | `<input type="radio">` | 比對值後加 `checked` | 多個相同 `name` 分組 |

### 📌 多選核取方塊（進階：陣列）

一個欄位可以有多個 checkbox（例如興趣嗜好），`name` 加 `[]` 讓 PHP 收成陣列：

 Copy

```
<?php
// DB stores JSON or comma-separated string — explode into an array after reading
$hobbies = explode(',', $u['hobbies'] ?? '');
$all = ['reading', 'gaming', 'coding', 'sports'];
foreach ($all as $h): ?>
  <label>
    <input type="checkbox" name="hobbies[]" value="<?= $h ?>"
      <?= in_array($h, $hobbies) ? 'checked' : '' ?>> <?= $h ?>
  </label>
<?php endforeach; ?>
```

 Copy

```
// save.php receives the array, joins it back into a string for DB storage
$hobbies = implode(',', $_POST['hobbies'] ?? []);
```

---

## ⚠️ 注意事項（常見坑位）

| 注意事項 | 說明 |
| --- | --- |
| 🚫 textarea 沒有 value | `<textarea value="...">` 瀏覽器會忽略，內容必須放在開合標籤之間 |
| ✅ checkbox 未勾選即缺席 | 未勾選的 checkbox 不會出現在 `$_POST`，寫回前要用 `isset()` 判斷並設 0 |
| 🔐 用 Prepared Statement | 永遠用 `prepare()` 與 `execute()` 綁定參數，防止 SQL Injection |
| 🛡️ 輸出要 escape | 資料放回 HTML 前用 `htmlspecialchars()`，防止 XSS 及引號破壞屬性 |
| 🎯 驗證 id | `filter_input(..., FILTER_VALIDATE_INT)` 拒絕非數字 id，查無資料回 404 |
| 📦 radio 分組靠 name | 同一組 radio 用相同 `name`，否則會變成可多選 |

---

## 🔗 參考連結

| 來源 | 連結 |
| --- | --- |
| Stack Overflow — checkbox update | [https://stackoverflow.com/questions/65607189](https://stackoverflow.com/questions/65607189) |
| techbloat — Get current value & show as selected | [https://techbloat.com/get-current-value-from-database-and-show-as-selected-on-edit-form-page-php.html](https://techbloat.com/get-current-value-from-database-and-show-as-selected-on-edit-form-page-php.html) |
| plus2net — PDO UPDATE 教學 | [https://plus2net.com/php_tutorial/pdo-update.php](https://plus2net.com/php_tutorial/pdo-update.php) |
| Quora — Fetch data to form (PDO) | [https://quora.com/How-do-I-fetch-data-from-a-database-to-form-in-PHP](https://quora.com/How-do-I-fetch-data-from-a-database-to-form-in-PHP) |

*資料來源：各技術教學及公開討論（2026 年 9 月）*
