PHP for the Web·Practice drills 5

Drill 11: Real project — Build a guestbook

Connect this example to a real project you could build.

Beginner 5 min read Lesson 120 of 300 Challenge included
What you will be able to do
  • Connect this example to a real project you could build.

Practice task

Connect this example to a real project you could build.

guestbook.phpPHP
<?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

Write your answer

Easy

Connect this example to a real project you could build.

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 in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Lesson 120 of 300 · 0% of course