Build a PHP Contact Form with Email and MySQL Storage - Full Guide for Beginners

July 3, 2025

Creating a contact form is one of the most common requirements for any website - whether it's a personal blog, portfolio, or business page. In this step-by-step guide, you'll learn how to create a fully functional contact form using PHP, store submissions in a MySQL database, and send emails using the built-in mail() function.

Perfect for beginners and intermediate developers alike, this guide walks through each step with code and explanation.

What You'll Learn

  • How to create a responsive HTML contact form
  • How to handle form submissions with PHP
  • Input sanitization and validation
  • How to send form data via email
  • How to store form submissions in a MySQL database
  • Security best practices

Step 1: Set Up the HTML Form (index.html or contact.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Contact Us</title>
</head>
<body>
    <h2>Contact Us</h2>
    <form action="contact.php" method="POST">
        <label for="name">Name:</label><br>
        <input type="text" name="name" id="name" required><br><br>

        <label for="email">Email:</label><br>
        <input type="email" name="email" id="email" required><br><br>

        <label for="message">Message:</label><br>
        <textarea name="message" id="message" rows="5" required></textarea><br><br>

        <button type="submit" name="submit">Send</button>
    </form>
</body>
</html>

Step 2: Create the MySQL Database and Table

Log in to your MySQL database and run the following:

CREATE DATABASE contact_db;

USE contact_db;

CREATE TABLE messages (
    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
);

Step 3: Create the PHP Script to Process Form (contact.php)

<?php
// Check if the form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // 1. Sanitize input
    $name = htmlspecialchars(strip_tags(trim($_POST["name"])));
    $email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
    $message = htmlspecialchars(strip_tags(trim($_POST["message"])));

    // 2. Basic validation
    if (!empty($name) && !empty($email) && !empty($message) && filter_var($email, FILTER_VALIDATE_EMAIL)) {

        // 3. Store in MySQL
        $host = 'localhost';
        $user = 'root';         // replace with your DB username
        $pass = '';             // replace with your DB password
        $db   = 'contact_db';

        $conn = new mysqli($host, $user, $pass, $db);

        if ($conn->connect_error) {
            die("Database connection failed: " . $conn->connect_error);
        }

        $stmt = $conn->prepare("INSERT INTO messages (name, email, message) VALUES (?, ?, ?)");
        $stmt->bind_param("sss", $name, $email, $message);

        if ($stmt->execute()) {
            // 4. Send email
            $to = "you@example.com"; // Replace with your email
            $subject = "New Contact Form Submission";
            $body = "Name: $name\nEmail: $email\n\nMessage:\n$message";
            $headers = "From: $email";

            if (mail($to, $subject, $body, $headers)) {
                echo "Thank you! Your message has been sent.";
            } else {
                echo "Message stored but email failed to send.";
            }
        } else {
            echo "Error: " . $stmt->error;
        }

        $stmt->close();
        $conn->close();
    } else {
        echo "Please fill all fields correctly.";
    }
} else {
    echo "Invalid request method.";
}
?>

Security Best Practices

  • Sanitize all input: Prevent XSS and SQL injection.
  • Validate email: Use FILTER_VALIDATE_EMAIL.
  • Use prepared statements: Avoid raw queries.
  • Never expose DB credentials in public repos.
  • Add CAPTCHA to avoid spam (optional).

Troubleshooting Tips

  • If email doesn’t send, check:
    • PHP mail() function is enabled
    • Your server allows sending emails
    • Use tools like PHPMailer for production
  • If the database doesn't connect:
    • Double-check host, username, password, and DB name
    • Ensure MySQL server is running

Bonus: Redirect After Submission

To redirect to a thank-you page after successful submission:

header("Location: thankyou.html");
exit;

Place it after the mail() function if all goes well.

Summary

You just learned how to:

  • Build a responsive HTML form
  • Process and validate form data in PHP
  • Store contact messages in a MySQL database
  • Send an email notification with user input

This is a practical, real-world example for beginner PHP developers to understand full-stack interaction from form to database to mail.

Comments ()