Step 1 Create a Contact From.
          Create a contact form giving below with simple HTML5 validation and save it with .php extension. Value which will be written between the double quotes in attribute Name like name=”u_name” in input tags work as a variable name. These attributes will contain the data from the form that we will use to save in our database by retrieving these value in our thankyou.php page. There are two methods to send your form data to your PHP page: GET and POST. I will be using POST as it hides the user data and there is no limit to send data.

For styling you can use your own CSS.

<!DOCTYPE html>
<title> Simple PHP contact form with MySQL and Form Validation </title>
<h3> Contact US</h3>
<form action="thankyou.php" method="post">
  <input type="text" name="u_name" required><br>

  <input type="email" name="u_email" required><br>

  <input type="text" name="subj" required><br>

  <input type="text" name="message" required><br>
<input type="submit" value="Submit"><br>


Step 2: Create Database

Open your localhost/phpmyadmin and click “New” button.

Step 3: Create Table

                        Now, open your newly created database and create a new table name it tb_cform. Your table will contain 5 fields, namely, ID (integer auto_increment), u_name (text), u_email (text), subj (text), and message (text).

We have used integer for ID because it will be a counter for people who have filled this form. I have checked it the A_I (auto_increment) box. By adding auto_increment, values increase by a single digit whenever a new response is added in the database. I am using text for other fields, though.

Step 4: Create Database Connection

                         To connect to your database, create a new PHP file. Name it connection.php and save it in the same folder where you have save your form. Fill the user and pass variables with the values that you have used for login into phpMyAdmin. If you have logged in to phpMyAdmin without any username and password, then leave it as mentioned in the following code.


function Connect()
 $dbhost = "localhost";
 $dbuser = "root";
 $dbpass = "";
 $dbname = "responses";

 // Create connection
 $conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname) or die($conn->connect_error);

 return $conn;

Step 5: Create Insert Function


require 'connection.php';
$conn    = Connect();
$name    = $conn->real_escape_string($_POST['u_name']);
$email   = $conn->real_escape_string($_POST['u_email']);
$subj    = $conn->real_escape_string($_POST['subj']);
$message = $conn->real_escape_string($_POST['message']);
$query   = "INSERT into tb_cform (u_name,u_email,subj,message) VALUES('" . $name . "','" . $email . "','" . $subj . "','" . $message . "')";
$success = $conn->query($query);

if (!$success) {
    die("Couldn't enter data: ".$conn->error);


echo "Thank You For Contacting Us <br>";



Step 6: Run It

Run your form by opening your browser and go to localhost/ContactForm/index.php


Post a Comment