🔥 Your ₹599 Course Awaits — Grab It Before It’s Gone!

Join thousands of learners building their careers with Prime Inspire. Your exclusive ₹599 coupon is just one click away.

Subscription Form

Build a Secure Feedback Form with PHP & MySQL

Want to let users leave feedback and store it safely in your MySQL database?
This tutorial will show you exactly how to build a secure, functional feedback form using HTML5, PHP 8 (functional style), and MySQL – perfect for websites, portfolios, or beginner PHP projects.

Build a Secure Feedback Form with PHP & MySQL

What You’ll Build

A complete feedback system with:

✅ Clean feedback form
✅ PHP server-side validation
✅ Secure MySQL storage using prepared statements
✅ Sanitization to protect from XSS
✅ Modular PHP (functional)
✅ Beginner-friendly + scalable

Project Folder Structure

Here’s how your final folder will look:

feedback-form/
├── index.html         → The feedback form UI
├── submit.php         → Handles submission securely
├── functions.php      → All the helper functions (modular)
└── db.sql             → SQL script for table setup

Step 1: Create Your MySQL Database

We’ll start by creating the database and table to store the feedback.

SQL Code (db.sql)

CREATE DATABASE feedback_db;

USE feedback_db;

CREATE TABLE feedbacks (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(100) NOT NULL,
  email VARCHAR(100) NOT NULL,
  message TEXT NOT NULL,
  submitted_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Code language: PHP (php)

📝 Tip: Use phpMyAdmin or CLI (e.g., mysql -u root -p) to execute the SQL.

Step 2: Build the Feedback Form UI

Create a simple HTML form to collect name, email, and message.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Feedback Form</title>
  <style>
    body {
      font-family: sans-serif;
      padding: 20px;
      max-width: 600px;
      margin: auto;
    }
    input, textarea {
      width: 100%;
      padding: 10px;
      margin: 6px 0 16px;
      border: 1px solid #ccc;
      border-radius: 6px;
    }
    button {
      padding: 10px 20px;
      background: #0066cc;
      color: #fff;
      border: none;
      border-radius: 6px;
      cursor: pointer;
    }
    button:hover {
      background: #004999;
    }
  </style>
</head>
<body>

  <h2>Leave Your Feedback</h2>
  <form action="submit.php" method="POST" novalidate>
    <label>Name</label>
    <input type="text" name="name" required>

    <label>Email</label>
    <input type="email" name="email" required>

    <label>Message</label>
    <textarea name="message" rows="5" required></textarea>

    <button type="submit">Submit Feedback</button>
  </form>

</body>
</html>
Code language: HTML, XML (xml)

novalidate disables browser validation so we can handle it ourselves in PHP.

Step 3: Create PHP Helper Functions

Let’s write our functional PHP logic inside a reusable functions.php file.

functions.php

<?php

function db_connect(): mysqli {
    $conn = new mysqli('localhost', 'root', '', 'feedback_db');
    if ($conn->connect_error) {
        die("DB connection failed: " . $conn->connect_error);
    }
    return $conn;
}

function sanitize(string $data): string {
    return htmlspecialchars(trim($data), ENT_QUOTES, 'UTF-8');
}

function is_valid_email(string $email): bool {
    return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}

function save_feedback(mysqli $conn, string $name, string $email, string $message): bool {
    $stmt = $conn->prepare("INSERT INTO feedbacks (name, email, message) VALUES (?, ?, ?)");
    $stmt->bind_param("sss", $name, $email, $message);
    return $stmt->execute();
}
Code language: HTML, XML (xml)

✅ Modular functions
✅ Prepared statements for security
✅ Email validation + XSS protection

Step 4: Handle Form Submission Securely

Now let’s write submit.php to process the feedback form, sanitize inputs, validate them, and save to MySQL.

submit.php

<?php
require 'functions.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = sanitize($_POST['name'] ?? '');
    $email = sanitize($_POST['email'] ?? '');
    $message = sanitize($_POST['message'] ?? '');

    if (empty($name) || empty($email) || empty($message)) {
        die("❌ All fields are required.");
    }

    if (!is_valid_email($email)) {
        die("❌ Please enter a valid email address.");
    }

    $conn = db_connect();
    $success = save_feedback($conn, $name, $email, $message);
    $conn->close();

    if ($success) {
        echo "✅ Thank you! Your feedback has been submitted.";
    } else {
        echo "❌ Oops! Something went wrong. Please try again later.";
    }
} else {
    echo "🚫 Access Denied.";
}
Code language: HTML, XML (xml)

Step 5: Security Best Practices

Let’s lock this down, Raahi. No loopholes, no leaks!

ThreatWhat We Did
SQL InjectionUsed prepare() with bound parameters
XSSSanitized inputs using htmlspecialchars()
Email InjectionValidated with filter_var()
Error DisclosureAvoided showing internal SQL errors in production
CSRF (Optional)Can be added using session-based token system

Want to go even further? Add Google reCAPTCHA, CSRF tokens, or server-side email alerts.

Step 6: Test Your Feedback Form

Try submitting:

  • Empty fields → ❌ Shows error
  • Invalid email → ❌ Shows error
  • Valid submission → ✅ Saves in database
  • Go check feedbacks table in phpMyAdmin!

Bonus Tips & Ideas

You can extend this form by adding:

  • 🌐 AJAX for real-time feedback without page reload
  • ✉️ Send feedback to your email
  • 📊 Admin dashboard to view/manage submissions
  • 🧼 Spam filtering or reCAPTCHA
  • 🎨 Glassmorphic UI

Final Thoughts

This is more than just a form. It’s a mini-project that teaches:

  • Functional PHP structure
  • Secure coding practices
  • Working with databases
  • Clean form design
  • Real-world use cases

Whether you’re a beginner or brushing up, this simple project is powerful and practical.

Download Full Project Files

You can clone or download the full source code here:
Download Source Code Files


Discover more from Prime Inspire

Subscribe to get the latest posts sent to your email.

We’d love to hear your thoughts! Share your ideas below 💡

Scroll to Top

Discover more from Prime Inspire

Subscribe now to keep reading and get access to the full archive.

Continue reading