Opening a task and saving it are separate jobs
Complete a task in lesson eight and imagine that its title has a typo. The edit page needs to read the old title first. Saving needs a new title from the form. Let’s build the read path before the write path.
Look up the title by ID
Append this to app/functions.php. fetch() reads one row. It returns false when no row matches, and the function expresses that as null.
function findTask(PDO $pdo, int $id): ?array
{
$statement = $pdo->prepare('SELECT id, title, done FROM tasks WHERE id = ?');
$statement->execute([$id]);
$task = $statement->fetch();
return $task === false ? null : $task;
}
In public/index.php, add $editing = null; after the session token and before the other form variables. Put this block below $input = ''; and above the POST handler.
if (isset($_GET['edit'])) {
$id = positiveId($_GET['edit']);
$editing = $id === null ? null : findTask($pdo, $id);
if ($editing === null) {
http_response_code(404);
exit('Task not found.');
}
$input = $editing['title'];
}
An invalid or missing ID returns 404. A found task supplies $input, which the form already uses. Try /?edit=1 for an existing ID and look for the old title. Leave the submit button alone for now. The form still sends an add action at this point.
Let one form do either job
In app/view.php, add this link after each task’s status form and before </li>.
<a href="/?edit=<?= (int) $task['id'] ?>">Edit</a>
In the main form, replace the fixed hidden action=add field with the block below. Keep the existing csrf field. An edit sends the action and row ID; a new task sends add.
<input type="hidden" name="action" value="<?= $editing ? 'edit' : 'add' ?>">
<?php if ($editing): ?>
<input type="hidden" name="id" value="<?= (int) $editing['id'] ?>">
<?php endif; ?>
Replace the button as shown. Put the cancel link immediately after the closing form tag.
<button><?= $editing ? 'Save changes' : 'Add task' ?></button>
<?php if ($editing): ?><p><a href="/">Cancel editing</a></p><?php endif; ?>
Teach PHP to save an edit
Keep the status action inside the POST handler. Replace the add-only check below it with this block. On an edit, load the row again so the form can remain in edit mode if validation fails.
if (!in_array($action, ['add', 'edit'], true)) {
http_response_code(400);
exit('Invalid action.');
}
if ($action === 'edit') {
$id = positiveId($_POST['id'] ?? null);
$editing = $id === null ? null : findTask($pdo, $id);
if ($editing === null) {
http_response_code(404);
exit('Task not found.');
}
}
Inside the successful validation branch, replace the INSERT lines with this choice. Keep redirectToList() immediately underneath it.
if ($action === 'edit') {
$statement = $pdo->prepare('UPDATE tasks SET title = ? WHERE id = ?');
$statement->execute([$title, $id]);
} else {
$statement = $pdo->prepare('INSERT INTO tasks (title) VALUES (?)');
$statement->execute([$title]);
}
Open a completed task. Submit spaces first. The form reports an error and MySQL keeps its title. Then save a valid title. The list shows the new title with the same completion status because the UPDATE changes only title.
Complete working files
Start with the files that change in this lesson. If you completed the previous lesson, the other files are already in your project.
public/index.php
<?php
declare(strict_types=1);
require __DIR__ . '/../app/functions.php';
$pdo = require __DIR__ . '/../app/db.php';
session_start();
$_SESSION['csrf'] ??= bin2hex(random_bytes(32));
$csrf = $_SESSION['csrf'];
$editing = null;
$error = null;
$input = '';
if (isset($_GET['edit'])) {
$id = positiveId($_GET['edit']);
$editing = $id === null ? null : findTask($pdo, $id);
if ($editing === null) {
http_response_code(404);
exit('Task not found.');
}
$input = $editing['title'];
}
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
$submittedToken = $_POST['csrf'] ?? null;
if (!is_string($submittedToken) || !hash_equals($csrf, $submittedToken)) {
http_response_code(403);
exit('Invalid form token.');
}
$action = $_POST['action'] ?? '';
if ($action === 'state') {
$id = positiveId($_POST['id'] ?? null);
$done = $_POST['done'] ?? null;
if ($id === null || !in_array($done, ['0', '1'], true)) {
http_response_code(400);
exit('Invalid task state.');
}
$statement = $pdo->prepare('UPDATE tasks SET done = ? WHERE id = ?');
$statement->execute([(int) $done, $id]);
redirectToList();
}
if (!in_array($action, ['add', 'edit'], true)) {
http_response_code(400);
exit('Invalid action.');
}
if ($action === 'edit') {
$id = positiveId($_POST['id'] ?? null);
$editing = $id === null ? null : findTask($pdo, $id);
if ($editing === null) {
http_response_code(404);
exit('Task not found.');
}
}
$input = is_string($_POST['title'] ?? null) ? $_POST['title'] : '';
$title = validateTitle($input);
if ($title === null) {
http_response_code(422);
$error = 'Enter a title of 1 to 120 bytes.';
} else {
if ($action === 'edit') {
$statement = $pdo->prepare('UPDATE tasks SET title = ? WHERE id = ?');
$statement->execute([$title, $id]);
} else {
$statement = $pdo->prepare('INSERT INTO tasks (title) VALUES (?)');
$statement->execute([$title]);
}
redirectToList();
}
}
$filter = $_GET['filter'] ?? 'all';
if (!in_array($filter, ['all', 'pending', 'done'], true)) {
$filter = 'all';
}
if ($filter === 'all') {
$tasks = $pdo->query('SELECT id, title, done FROM tasks ORDER BY id')->fetchAll();
} else {
$statement = $pdo->prepare('SELECT id, title, done FROM tasks WHERE done = ? ORDER BY id');
$statement->execute([$filter === 'done' ? 1 : 0]);
$tasks = $statement->fetchAll();
}
require __DIR__ . '/../app/view.php';
app/view.php
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>Task list</title>
<h1>Task list</h1>
<?php if ($error !== null): ?>
<p role="alert"><?= e($error) ?></p>
<?php endif; ?>
<form method="post" action="/">
<input type="hidden" name="csrf" value="<?= e($csrf) ?>">
<input type="hidden" name="action" value="<?= $editing ? 'edit' : 'add' ?>">
<?php if ($editing): ?>
<input type="hidden" name="id" value="<?= (int) $editing['id'] ?>">
<?php endif; ?>
<label for="title">Task title</label>
<input id="title" name="title" value="<?= e($input) ?>" required>
<button><?= $editing ? 'Save changes' : 'Add task' ?></button>
</form>
<?php if ($editing): ?><p><a href="/">Cancel editing</a></p><?php endif; ?>
<nav aria-label="Task filters">
<a href="/?filter=all">All</a>
<a href="/?filter=pending">Pending</a>
<a href="/?filter=done">Completed</a>
</nav>
<p>Filter: <?= e($filter) ?></p>
<?php if ($tasks === []): ?><p>No matching tasks.</p><?php endif; ?>
<ul>
<?php foreach ($tasks as $task): ?>
<li>
<?= e($task['title']) ?> — <?= $task['done'] ? 'Completed' : 'Pending' ?>
<form method="post" action="/">
<input type="hidden" name="csrf" value="<?= e($csrf) ?>">
<input type="hidden" name="action" value="state">
<input type="hidden" name="id" value="<?= (int) $task['id'] ?>">
<input type="hidden" name="done" value="<?= $task['done'] ? 0 : 1 ?>">
<button><?= $task['done'] ? 'Mark pending' : 'Complete' ?></button>
</form>
<a href="/?edit=<?= (int) $task['id'] ?>">Edit</a>
</li>
<?php endforeach; ?>
</ul>
</html>
app/functions.php
<?php
declare(strict_types=1);
function e(string $value): string
{
return htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
function validateTitle(mixed $value): ?string
{
if (!is_string($value)) {
return null;
}
$title = trim($value);
return $title !== '' && strlen($title) <= 120 ? $title : null;
}
function redirectToList(): never
{
header('Location: /', true, 303);
exit;
}
function positiveId(mixed $value): ?int
{
if (!is_string($value)) {
return null;
}
$id = filter_var($value, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
return $id === false ? null : $id;
}
function findTask(PDO $pdo, int $id): ?array
{
$statement = $pdo->prepare('SELECT id, title, done FROM tasks WHERE id = ?');
$statement->execute([$id]);
$task = $statement->fetch();
return $task === false ? null : $task;
}
Files carried forward from the previous lesson
app/db.php
<?php
declare(strict_types=1);
$host = getenv('DB_HOST') ?: '127.0.0.1';
$port = getenv('DB_PORT') ?: '3306';
$database = getenv('DB_NAME') ?: 'php_tasks';
$user = getenv('DB_USER') ?: 'php_tasks';
$password = getenv('DB_PASS');
$dsn = "mysql:host=$host;port=$port;dbname=$database;charset=utf8mb4";
return new PDO($dsn, $user, $password === false ? '' : $password, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
]);
schema.sql
CREATE TABLE tasks (
id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(120) NOT NULL,
done TINYINT UNSIGNED NOT NULL DEFAULT 0,
CHECK (done IN (0, 1))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
seed.sql
INSERT INTO tasks (title, done)
VALUES ('Read the lesson', 1), ('Run the example', 0);
After saving the files, run php -S 127.0.0.1:8000 -t public in the project folder and open http://127.0.0.1:8000/. If the server is already running from that project folder, refresh the page.