---
title: "DB-Edit MySQL Record (Read Data to Populate an HTML Form and Write Back) (en)"
description: "This guide shows how to edit a MySQL record with PHP: read one row by id, populate an HTML form, then write the changes back with UPDATE. It covers four field types — single-line text, multi-line text, checkbox, and radio button."
url: "https://aaronchan.com/kb/db-edit-mysql-record/"
updated: "2026-09-18"
category: "Code-php+MySQL (en)"
---

# DB-Edit MySQL Record (Read Data to Populate an HTML Form and Write Back) (en)

This guide shows how to edit a MySQL record with PHP: read one row by `id`, populate an HTML form, then write the changes back with `UPDATE`. It covers four field types — single-line text, multi-line text, checkbox, and radio button.

## 🧭 Workflow Overview

Editing a record follows the same three steps for every field type:

| Step | Action | Description |
| --- | --- | --- |
| 1️⃣ | **Retrieve** | Query the database by `id` and fetch the record |
| 2️⃣ | **Populate** | Fill the fetched values into the matching form fields |
| 3️⃣ | **Write back** | After submit, save the new values back with `UPDATE` |

---

## 🗄️ Table Structure

Create a `users` table where the four columns match the four form input types:

 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
);
```

---

## 🔌 Database Connection (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');
}
```

---

## 📖 Read + Populate the Form (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>
```

---

## 💾 Write Back to the Database (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;
```

---

## 🧩 Four Field Types — Populate Comparison

| Field type | HTML Element | How to populate | Key attribute |
| --- | --- | --- | --- |
| Single-line text | `<input type="text">` | `value` attribute | `value="..."` |
| Multi-line text | `<textarea>` | content between the tags | no `value` attribute |
| Checkbox | `<input type="checkbox">` | `checked` attribute | value is 1/0 |
| Radio button | `<input type="radio">` | compare value, then add `checked` | grouped by the same `name` |

### 📌 Multi-select Checkbox (Advanced: Array)

A field can have multiple checkboxes (e.g. hobbies); add `[]` to `name` so PHP receives an array:

 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'] ?? []);
```

---

## ⚠️ Gotchas

| Gotcha | Note |
| --- | --- |
| 🚫 textarea has no value | `<textarea value="...">` is ignored by the browser — the content must go between the opening and closing tags |
| ✅ checkbox is absent when unchecked | an unchecked checkbox will not appear in `$_POST` — check with `isset()` and set 0 before writing back |
| 🔐 Use prepared statements | always bind parameters with `prepare()` and `execute()` to prevent SQL injection |
| 🛡️ Escape output | use `htmlspecialchars()` before putting data back into HTML, to prevent XSS and broken attributes |
| 🎯 Validate the id | `filter_input(..., FILTER_VALIDATE_INT)` rejects non-numeric ids; return 404 when no record is found |
| 📦 Radio buttons group by name | radios in the same group must share the same `name`, otherwise they become multi-selectable |

---

## 🔗 References

| Source | Link |
| --- | --- |
| 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 tutorial | [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) |

*Sources: various technical tutorials and public discussions (Sep 2026)*
