November 19, 2026 - 11:04
PHP Lesson 07 — Change a Task's Completion Status Image
PHP Tutorials

PHP Lesson 07 — Change a Task's Completion Status

0 Comments

Two tasks have the same title

Use lesson six to add “Buy tea” twice and inspect the local table.

SQL
SELECT id, title, done FROM tasks WHERE title = 'Buy tea' ORDER BY id;

The titles are identical. If the button sends just the title, PHP does not know which one you chose. Each row already has a distinct id. Send that.

Give each row its own button

In app/view.php, place this form inside foreach, just before the closing </li>. Keep the add form above the list.

PHP
    <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>

Each turn has a different $task['id']. The hidden done field holds the desired state. A pending row sends 1, a completed row sends 0. The action tells PHP this is the status form.

Check the ID and update one row

Append this helper to app/functions.php. The form sends text. The function returns a positive integer or null when it cannot accept the value.

PHP
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;
}

In the POST handler in public/index.php, add the following just after $action = $_POST['action'] ?? '';. This runs after the token check and before the add-only check.

PHP
    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();
    }

The two placeholders take the desired state and row ID in that order. WHERE id = ? limits the update to one row. Without a condition an UPDATE covers the whole table. The redirect ends the request, so the status form never runs the add handler.

Complete the first “Buy tea” and repeat the query. Only the selected ID should have a status of 1. The new button label should say “Mark pending.”

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
<?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'];
$error = null;
$input = '';

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'], true)) {
        http_response_code(400);
        exit('Invalid action.');
    }
    $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 {
        $statement = $pdo->prepare('INSERT INTO tasks (title) VALUES (?)');
        $statement->execute([$title]);
        redirectToList();
    }
}

$tasks = $pdo->query('SELECT id, title, done FROM tasks ORDER BY id')->fetchAll();

require __DIR__ . '/../app/view.php';
app/view.php
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="add">
  <label for="title">Task title</label>
  <input id="title" name="title" value="<?= e($input) ?>" required>
  <button>Add task</button>
</form>
<?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>
  </li>
<?php endforeach; ?>
</ul>
</html>
app/functions.php
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;
}
Files carried forward from the previous lesson
app/db.php
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
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
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.

Related Articles

Comments (0)

No comments yet. Be the first to comment!

Leave a Comment