Aral Code

Databases Lesson 17 of 17

PHP Final Project — Student Feedback Board with MySQL

Build a complete PHP and MySQL web app — a feedback board where students post messages — with validation, prepared statements, escaping, CSRF protection and a simple admin delete.

Let's build a real web app: a feedback board where students post suggestions for their school, and a teacher can remove inappropriate posts. It brings together forms, validation, sessions, PDO and security.

The database

Run this in phpMyAdmin:

CREATE DATABASE feedback CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
USE feedback;

CREATE TABLE posts (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(60) NOT NULL,
  message VARCHAR(500) NOT NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);

Project files

htdocs/feedback/
├── db.php        connection
├── index.php     the board: list + form
└── delete.php    teacher-only delete

db.php

<?php
session_start();
$pdo = new PDO("mysql:host=localhost;dbname=feedback;charset=utf8mb4", "root", "", [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);

// A random token to protect forms from CSRF attacks
$_SESSION["csrf"] ??= bin2hex(random_bytes(16));

function e(string $s): string {
    return htmlspecialchars($s, ENT_QUOTES, "UTF-8");
}

index.php

<?php
require "db.php";

$errors = [];
$name = "";
$message = "";

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    if (!hash_equals($_SESSION["csrf"], $_POST["csrf"] ?? "")) {
        exit("Invalid form submission.");
    }
    $name = trim($_POST["name"] ?? "");
    $message = trim($_POST["message"] ?? "");

    if ($name === "" || mb_strlen($name) > 60) $errors[] = "Name is required (max 60 characters).";
    if (mb_strlen($message) < 5 || mb_strlen($message) > 500) $errors[] = "Message must be 5 to 500 characters.";

    if (!$errors) {
        $stmt = $pdo->prepare("INSERT INTO posts (name, message) VALUES (?, ?)");
        $stmt->execute([$name, $message]);
        header("Location: index.php");   // Post/Redirect/Get
        exit;
    }
}

$posts = $pdo->query("SELECT id, name, message, created_at FROM posts ORDER BY created_at DESC LIMIT 50")->fetchAll();
$isTeacher = ($_SESSION["role"] ?? "") === "teacher";
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Feedback Board</title>
  <style>
    body { font-family: system-ui, sans-serif; max-width: 640px; margin: 24px auto; padding: 0 14px; }
    .post { border: 1px solid #ddd; border-radius: 10px; padding: 12px; margin: 10px 0; }
    .meta { color: #666; font-size: 14px; }
    .error { color: #b4372b; }
    textarea, input { width: 100%; padding: 10px; font: inherit; box-sizing: border-box; }
  </style>
</head>
<body>
  <h1>💬 Feedback Board</h1>

  <form method="post">
    <input type="hidden" name="csrf" value="<?= e($_SESSION["csrf"]) ?>">
    <p><input name="name" placeholder="Your name" value="<?= e($name) ?>"></p>
    <p><textarea name="message" rows="3" placeholder="Your suggestion for the school"><?= e($message) ?></textarea></p>
    <?php foreach ($errors as $err): ?>
      <p class="error"><?= e($err) ?></p>
    <?php endforeach; ?>
    <button>Post</button>
  </form>

  <?php foreach ($posts as $p): ?>
    <div class="post">
      <p><?= nl2br(e($p["message"])) ?></p>
      <p class="meta">— <?= e($p["name"]) ?>, <?= e($p["created_at"]) ?>
        <?php if ($isTeacher): ?>
          <form method="post" action="delete.php" style="display:inline">
            <input type="hidden" name="csrf" value="<?= e($_SESSION["csrf"]) ?>">
            <input type="hidden" name="id" value="<?= (int) $p["id"] ?>">
            <button>Delete</button>
          </form>
        <?php endif; ?>
      </p>
    </div>
  <?php endforeach; ?>
</body>
</html>

delete.php

<?php
require "db.php";
if (($_SESSION["role"] ?? "") !== "teacher"
    || !hash_equals($_SESSION["csrf"], $_POST["csrf"] ?? "")) {
    http_response_code(403);
    exit("Not allowed.");
}
$stmt = $pdo->prepare("DELETE FROM posts WHERE id = ?");
$stmt->execute([(int) ($_POST["id"] ?? 0)]);
header("Location: index.php");
exit;

To try the teacher features, add a login page like the one in the Sessions lesson that sets $_SESSION["role"] = "teacher" after checking a hashed password.

Security features in this project

FeatureProtects against
Prepared statementsSQL injection
e() on every outputXSS (scripts in messages)
Validation with length limitsEmpty or huge posts
CSRF token in formsOther sites submitting forms on a user's behalf
Role check in delete.phpStudents deleting posts
Delete uses POST, not a linkAccidental deletes by link previews or crawlers
Redirect after postingDuplicate posts on refresh

nl2br(e(...)) escapes first, then turns new lines into <br>, so line breaks show without allowing HTML.

Challenges

  1. Add a teacher login with a users table and password_hash.
  2. Add "likes" with a button and a likes column.
  3. Add pagination with LIMIT ? OFFSET ?.
  4. Add categories (Facilities, Canteen, Events) with a filter.
  5. Style it with Bootstrap.

What's next?

Congratulations on finishing the PHP course! 🎉 You can now build real web apps with a database. Next, explore Laravel, a popular PHP framework that adds routing, templates and authentication; learn MySQL in more depth; or host your project on a PHP web host to share it.

Quick Quiz

Check what you learned. Walang grade ito, practice lang. 🙂

1. What is the CSRF token for?
2. Why does delete use a POST form instead of a link?
3. What does nl2br(e($text)) do?
4. Why redirect after inserting a post?

By Sir Reyel · Last updated 2026-12-04