Build a guestbook
Combine forms, validation, PDO, escaping and pagination in one small application.
What you will be able to do
- Validate before writing to the database.
- Escape at output, not at storage time.
- Paginate with LIMIT and OFFSET using bound integers.
- Keep the controller and the template in separate sections.
In plain English
A guestbook touches every skill in the course: read a form, validate the fields, insert a row with a prepared statement, then list rows with escaping and pagination. Build it once end to end and the pieces stop feeling separate.
<?php
$pdo = new PDO('sqlite:' . __DIR__ . '/guestbook.db', null, null, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);
$pdo->exec('CREATE TABLE IF NOT EXISTS messages (
id INTEGER PRIMARY KEY, name TEXT NOT NULL, body TEXT NOT NULL, created_at TEXT NOT NULL
)');
$error = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$name = trim($_POST['name'] ?? '');
$body = trim($_POST['body'] ?? '');
if ($name === '' || $body === '') {
$error = 'Name and message are required.';
} else {
$stmt = $pdo->prepare('INSERT INTO messages (name, body, created_at) VALUES (?, ?, ?)');
$stmt->execute([$name, $body, date('c')]);
}
}
$page = max(1, (int) ($_GET['page'] ?? 1));
$offset = ($page - 1) * 5;
$stmt = $pdo->prepare('SELECT * FROM messages ORDER BY id DESC LIMIT 5 OFFSET ?');
$stmt->bindValue(1, $offset, PDO::PARAM_INT);
$stmt->execute();
$messages = $stmt->fetchAll();
?>
<?php foreach ($messages as $message): ?>
<article>
<h2><?= htmlspecialchars($message['name']) ?></h2>
<p><?= nl2br(htmlspecialchars($message['body'])) ?></p>
</article>
<?php endforeach; ?>Your turn
HardAdd a delete action
Add a POST-only delete endpoint that requires a CSRF token before deleting a message by id.
PHP · starter
if ($_SERVER['REQUEST_METHOD'] === 'POST') { }Check your understanding before moving on.
Knowledge checkQuestion 1
Which function should wrap user text before printing it into HTML?
Select an answer to continue
Study tools
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign inFinished reading?
Lock in what you just learned.
0%
Mark this lesson complete to save your place and move one step closer to the certificate.