Drill 16: Recall — Build a guestbook
Close the lesson and reproduce the example from memory.
What you will be able to do
- Close the lesson and reproduce the example from memory.
Practice task
Close the lesson and reproduce the example from memory.
<?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
EasyWrite your answer
Close the lesson and reproduce the example from memory.
TEXT · starter
Your answer…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.