November 19, 2026 - 11:04
PHP Lesson 06 — Save a Task and Redirect Back to the List Image
PHP Tutorials

PHP Lesson 06 — Save a Task and Redirect Back to the List

0 Comments

The preview worked. Where is the row?

Submit “Buy tea” in lesson five. The title appears in the preview. Run this query and look for it in MySQL. The missing row tells us what to add to the form handler.

SQL
SELECT id, title FROM tasks ORDER BY id;

Give a successful save somewhere to go

Append this helper to app/functions.php. It sends the browser back to the list after a successful write. header() sets response headers, so call the helper before any HTML is printed. exit ends the request, which is what the never return type describes.

PHP
function redirectToList(): never
{
    header('Location: /', true, 303);
    exit;
}

If a POST renders HTML directly, refreshing can prompt the browser to submit the same request again. A 303 sends it to the location with a new GET. The first request writes, the second reads.

Connect the form to the session

Add these lines immediately after the PDO connection in public/index.php. The session lets PHP recover the random token when the browser submits the next request.

PHP
session_start();
$_SESSION['csrf'] ??= bin2hex(random_bytes(32));
$csrf = $_SESSION['csrf'];

In app/view.php, add these two hidden fields just inside the form. action identifies what the form does. The token lets PHP compare the submission with the value it kept in the session.

PHP
  <input type="hidden" name="csrf" value="<?= e($csrf) ?>">
  <input type="hidden" name="action" value="add">

Change Preview task to Add task and remove the conditional Preview: paragraph below the form. You will see the result in the list.

Write the accepted title

In index.php, remove $preview = null;. Replace the old POST block with this one and keep the list query underneath it.

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

PHP checks that the token is a string and matches the session value. Then it checks the action and validates the title. An invalid title sets the error and returns the form. A valid title is passed separately for the question mark in the INSERT. Try “Ali's task.” The apostrophe should remain part of the stored value.

Open the browser's Network panel and add one task. Look for POST → 303 → GET, then refresh twice. The title should appear once and the SQL query should show one new row. Clicking Add twice is two separate POST submissions.

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 (!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' ?>
  </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;
}
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.

PDO prepare

Related Articles

Comments (0)

No comments yet. Be the first to comment!

Leave a Comment