DEV Community

Cover image for PHP crash course: Simple Contact Form
MD ARIFUL HAQUE
MD ARIFUL HAQUE

Posted on

PHP crash course: Simple Contact Form

A comprehensive contact form application built with PHP, jQuery, AJAX, Bootstrap, CSS, and MySQL. This form sends an email to the site owner upon submission. The form leverages a relational database to store contact details and manages communication effectively.

Database Schema

Create a MySQL database and a table for the contact form send email messages:

CREATE DATABASE contact_form_db;
USE contact_form_db;

CREATE TABLE contact_form_db (
   id INT AUTO_INCREMENT PRIMARY KEY,
   name VARCHAR(100) NOT NULL,
   email VARCHAR(100) NOT NULL,
   message TEXT NOT NULL,
   created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Enter fullscreen mode Exit fullscreen mode

Project Structure

simple-contact-form/
├── css/
│   └── styles.css
├── js/
│   └── script.js
├── config.php
├── db.php
├── index.php
├── process_form.php
├── README.md
└── send_email.php
Enter fullscreen mode Exit fullscreen mode

Configure the Database Connection:

  • Open the config.php file and update the database credentials.
<?php
   define('DB_HOST', 'localhost');
   define('DB_NAME', 'contact_form_db');
   define('DB_USER', 'root'); // Change if necessary
   define('DB_PASS', ''); // Change if necessary
?>
Enter fullscreen mode Exit fullscreen mode

Configuration File: db.php

<?php
   include 'config.php';
   // Database configuration
   $dsn = 'mysql:host='.DB_HOST.';dbname='.DB_NAME;
   $options = [
       PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
       PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
   ];

   try {
       $pdo = new PDO($dsn, DB_USER, DB_PASS, $options);
       $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
   } catch (PDOException $e) {
       die('Database connection failed: ' . $e->getMessage());
   }
?>
Enter fullscreen mode Exit fullscreen mode

Contact Form: index.html

<!DOCTYPE html>
<html lang="en">
   <head>
       <meta charset="UTF-8">
       <meta name="viewport" content="width=device-width, initial-scale=1.0">
       <title>Contact Form</title>
       <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
       <link rel="stylesheet" href="css/styles.css">
   </head>
   <body>
       <div class="container">
           <h2>Contact Us</h2>
           <form id="contactForm">
               <div class="form-group">
                   <label for="name">Name:</label>
                   <input type="text" class="form-control" id="name" name="name" required>
               </div>
               <div class="form-group">
                   <label for="email">Email:</label>
                   <input type="email" class="form-control" id="email" name="email" required>
               </div>
               <div class="form-group">
                   <label for="message">Message:</label>
                   <textarea class="form-control" id="message" name="message" rows="5" required></textarea>
               </div>
               <button type="submit" class="btn btn-primary">Submit</button>
           </form>
       </div>
       <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
       <script src="js/script.js"></script>
   </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Custom Styles: css/styles.css

body {
    padding-top: 50px;
}
.container {
    max-width: 600px;
    margin: auto;
}
Enter fullscreen mode Exit fullscreen mode

AJAX Submission: js/script.js

$(document).ready(function() {
    $('#contactForm').on('submit', function(event) {
        event.preventDefault();

        $.ajax({
            url: 'process_form.php',
            type: 'POST',
            data: $(this).serialize(),
            success: function(response) {
                alert('Message sent successfully!');
                $('#contactForm')[0].reset();
            },
            error: function(xhr, status, error) {
                alert('An error occurred: ' + error);
            }
        });
    });
});
Enter fullscreen mode Exit fullscreen mode

Handle Form Submission: process_form.php

<?php
require 'db.php';

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

        $stmt = $pdo->prepare("INSERT INTO messages (name, email, message) VALUES (:name, :email, :message)");
        $stmt->execute(['name' => $name, 'email' => $email, 'message' => $message]);

        require 'send_email.php';

        $email_body = "Name: $name\nEmail: $email\nMessage:\n$message";
        mail($to, $subject, $email_body, $headers);

        echo 'Message sent successfully!';
    }
} catch (PDOException $e) {
    echo 'Database error: ' . $e->getMessage();
}
?>
Enter fullscreen mode Exit fullscreen mode

Email Configuration: send_email.php

<?php
$to = 'youremail@example.com';
$subject = 'New Contact Form Message';
$headers = 'From: webmaster@example.com' . "\r\n" .
           'Reply-To: webmaster@example.com' . "\r\n" .
           'X-Mailer: PHP/' . phpversion();
?>
Enter fullscreen mode Exit fullscreen mode

Explanation

  1. Configuration (config.php): This file contains the database connection setup using PDO. It includes error handling for a failed connection.
  2. Contact Form (index.html): This file creates the contact form using Bootstrap for styling. It includes jQuery to handle form submission via AJAX.
  3. AJAX Script (js/script.js): Handles form submission using AJAX to send data to the server without reloading the page. It also fetches and displays messages dynamically.
  4. Submit Message (process_form.php): This script handles form submission. It inserts the contact details into the database and triggers email.
  5. Send Email (send_email.php): Uses PHPMailer to send an email notification to the site owner.
  6. CSS (css/style.css): Provides basic styling for the contact form.

This setup ensures that when a user submits the contact form, their details are saved in the database, and notifications are sent to the site owner via email.

Connecting Links

If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks 😍. Your support would mean a lot to me!

If you want more helpful content like this, feel free to follow me:

Source Code

Top comments (1)

Collapse
 
sreno77 profile image
Scott Reno

This is a good article for learning. I would mention that for a public facing website, you should consider using a framework such as Laravel.