Yogesh Chauhan's Blog

Learn to Make a Simple Contact Us Form using PHP and PDO-MySQL

in PHP on December 13, 2019

In this article I’ll show you how to make a contact us or feedback form for your contact us page. It’ll be nice option for your users to contact you from there.

This blog post will only contain simple form without CSS.

Step 1: Database

Let’s start with making a database table in MySQL. No matter what interface you are using you can execute following code in MySQL shell or phpmyadmin.

  `Name` varchar(50) NOT NULL,
  `Email` varchar(50) NOT NULL,
  `Company` varchar(50) NOT NULL,
  `Comments` text NOT NULL,
  PRIMARY KEY (`userID`)

As you can see the size of those columns are limited in my table but you can increase it as per your need and you can add more columns as per your need as well.

Step 2: Create a .php file.

Keep this file in your root folder so that you can easily add a link of this file to your website, which will become yourdomain.com/contact.php

Step 3: Add a database connection.

Lets add database connection to that file in the beginning.

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "the_coding_yogi_blog_demo";

As you can see I’ve added credentials for my local database file and you can use your local database credentials too but when you upload this form/file to your website folder on server, make sure to change the credentials as per your server’s database. If you don’t know them, just ask to the support team of your server.

Make sure to change the credentials as per your server’s database when you upload this file online.

Step 4: HTML form

Now, let’s make a simple HTML form in same PHP file.

<h2>Please Fill Out The Form</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">  
  Full Name: <input type="text" name="name" required>
  E-mail Address: <input type="text" name="email" required>
  Company: <input type="text" name="company">
  Comments/Feedback: <textarea name="comments" rows="5" cols="40" required></textarea>
  <input type="submit" name="submit" value="Submit">  

I’ve created very basic feedback form for demo purposes but you can create a very complex form with many more fields into it. 

All the input elements as well as submit button required name as we need to bind those fields with user inputs in PHP code. Do not forget those. I’ve kep the name, email and feedback fields as required as those are essentials to our message and for contact form data.

I assume you have basic understanding of how form works in PHP. If not, refer this Official Manual

If you want to understand why I have used htmlspecialchars() function in form action tag, then refer the following blog post. I’ve explained the possible hacker attack.

An Example of Cross-site Scripting (XSS) Attack in PHP and How to Avoid It?

Step 5: Database Connection

Connect to the database and add user inputs into the table.

$name = $email = $company = $comments = "";

  try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);

//code continues...

In the code I’m assigning the variables as empty values and then making the connection using PDO. In the next line, I am setting the error mode to exception.

$stmt = $conn->prepare("INSERT INTO feedback (Name,Email,Company,Comments) VALUES (:name, :email, :company, :comments)");
    $stmt->bindParam(':name', $name);
    $stmt->bindParam(':email', $email);
    $stmt->bindParam(':company', $company);
    $stmt->bindParam(':comments', $comments);

    $name = clean($_POST["name"]);
    $email = clean($_POST["email"]);
    $company = clean($_POST["company"]);
    $comments = clean($_POST["comments"]);

//code continues

After making the connection, we need to execute the SQL query  in order to insert data. So, the first line in the code above, prepares the SQL statement and then next few lines, binds the user input values to the INSERT values. After that, we need to execute that whole statement.

    echo "<div style='color:navy;'><h2>We Have Received Following Message From 
    echo "Your Name: ". $name;
    echo "<br>";
    echo "Your Email Address: " . $email;
    echo "<br>";
    echo "Your Company: ". $company;
    echo "<br>";
    echo "Your Comments: " . $comments;
    echo "<br>";
    echo "<h2>We will get back to you as soon as possible.</h2></div>";

//code continues

Now, if that goes through without any errors, we will display user this message about acknowledging user inputs. I’ve changed the color of that acknowledgement navy to make the fonts look different than the form fonts. You can use a nice CSS to make it look really pretty.

  catch(PDOException $e)
  echo "Error: " . $e->getMessage();

//code continues

If the INSERT query doesn’t go through and get stuck somewhere, the code above will be executed.

The error will be one of the errors from PHP which user might not be able to understand it. If you want, you can go ahead and change the error to user friendly errors so that they will understand what’s going on. I will cover more about that in upcoming blog post.

function clean($userInput) {
  $userInput = trim($userInput);
  $userInput = stripslashes($userInput);
  $userInput = htmlspecialchars($userInput);
  return $userInput;
$conn = null;


//end of the code

The function above cleans the user inputs.

To learn more about user input cleaning, read the following blog post.

Clean Form Input With These PHP Functions Before Inserting into Database

Now your full code is ready and you just need to add some HTML tags to make it perfect page.

Most Read

#1 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
Actions vs. Filters: hooks in WordPressWordPressAdvanced nesting in Sass (SCSS) using at-rootSCSSHow to obfuscate JavaScript code to hide it from View Source?JavaScriptPHP Login System using PDO Part 2: Login using Email or UsernamePHPRIGHT JOIN in PostgresPostgresHow to vertically and horizontally align text and image block (without flex or grid) in CSS?CSS