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.


DROP TABLE IF EXISTS `feedback`;
CREATE TABLE IF NOT EXISTS `feedback` (
  `userID` int(11) NOT NULL AUTO_INCREMENT,
  `Name` varchar(50) NOT NULL,
  `Email` varchar(50) NOT NULL,
  `Company` varchar(50) NOT NULL,
  `Comments` text NOT NULL,
  PRIMARY KEY (`userID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
COMMIT;

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.


<?php 
$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>
  <br><br>
  E-mail Address: <input type="text" name="email" required>
  <br><br>
  Company: <input type="text" name="company">
  <br><br>
  Comments/Feedback: <textarea name="comments" rows="5" cols="40" required></textarea>
  <br><br>
  <input type="submit" name="submit" value="Submit">  
</form>

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.


<?php
$name = $email = $company = $comments = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

//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"]);
    $stmt->execute();

//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 
    You:</h2>";
    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 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
How to show widgets on the Appearance tab in WordPress?WordPressIN and BETWEEN Operators in SQLSQL/MySQLFive common features of Angular template syntax (with examples)AngularHow to Install PHP composer in Mac OS Catalina?PHPWhat are components in Angular?AngularHow services and dependency injection work in Angular?Angular