Create Contact Form in PHP 7 with jQuery Validation

Last updated on by Digamber
A contact form is a primary tool for customer engagement. It allows site visitors to contact the site owner without putting an extra effort. It enhances your business growth exponentially. A contact form must be functionally good, and it should also be graphically interactive from a UI/UX perspective.

In this tutorial, we will learn how to create a contact form in PHP and store the customer information in the MySQL database. We will implement the form validation in the contact form using the most popular jQuery validation plugin.

Contact Form in PHP

This contact form will send a direct email to the recipient’s email address, and we will use PHP’s mail() function to achieve this task.

We will use the Bootstrap 4 form component to create the best PHP contact form. It builds the responsive contact form quickly, which adjusts its size based on device size, be it Desktop, Tablet, or Mobile.

After completing this tutorial, you will get a free PHP contact form, which lets you receive the business queries on the go. The good thing is you can use this contact form in your web application too.

If you are new to PHP web development then you must explore our detailed article on Building User Authentication in PHP.

Design Contact Form with Bootstrap

To create form UI, add bootstrap CSS in the head section to design a responsive contact form use bootstrap’s form component. Define the name, email, phone, subject, and message input field within the form tag.

To read the form values through name property, define enctype=”multipart/form-data” to encode the data that forms the body of the POST request.

<!doctype html>
<html>

<head>
  <meta charset="utf-8">
  <title>Contact Form in PHP</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
</head>

<body>

  <div class="container mt-5">
    <!-- Contact form -->
    <form action="" name="contactForm" method="post" enctype="multipart/form-data">
      <div class="form-group">
        <label>Name</label>
        <input type="text" class="form-control" name="name" id="name">
      </div>

      <div class="form-group">
        <label>Email</label>
        <input type="email" class="form-control" name="email" id="email">
      </div>

      <div class="form-group">
        <label>Phone</label>
        <input type="text" class="form-control" name="phone" id="phone">
      </div>

      <div class="form-group">
        <label>Subject</label>
        <input type="text" class="form-control" name="subject" id="subject">
      </div>

      <div class="form-group">
        <label>Message</label>
        <textarea class="form-control" name="message" id="message" rows="4"></textarea>
      </div>

      <input type="submit" name="send" value="Send" class="btn btn-dark btn-block">
    </form>
  </div>
</body>

</html>

Add custom CSS to style the contact form.

.container {
    max-width: 500px;
    margin: 50px auto;
    text-align: left;
    font-family: sans-serif;
}

form {
    border: 1px solid #1A33FF;
    background: #ecf5fc;
    padding: 40px 50px 45px;
}

.form-control:focus {
    border-color: #000;
    box-shadow: none;
}

label {
    font-weight: 600;
}

.error {
    color: red;
    font-weight: 400;
    display: block;
    padding: 6px 0;
    font-size: 14px;
}

.form-control.error {
    border-color: red;
    padding: .375rem .75rem;
}

Contact Form Validation with jQuery

Place jQuery and validation plugin links before the body tag closes.

<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.2/dist/jquery.validate.min.js"></script>

Validate the form using the validator methods, and you can also check out the plugin’s documentation here.

<script>
    $(function () {
        $("form[name='contactForm']").validate({
            // Define validation rules
            rules: {
                name: "required",
                email: "required",
                phone: "required",
                subject: "required",
                message: "required",
                name: {
                    required: true
                },
                email: {
                    required: true,
                    email: true
                },
                phone: {
                    required: true,
                    minlength: 10,
                    maxlength: 10,
                    number: true
                },
                subject: {
                    required: true
                },
                message: {
                    required: true
                }
            },
            // Specify validation error messages
            messages: {
                name: "Please provide a valid name.",
                email: {
                    required: "Please enter your email",
                    minlength: "Please enter a valid email address"
                },
                phone: {
                    required: "Please provide a phone number",
                    minlength: "Phone number must be min 10 characters long",
                    maxlength: "Phone number must not be more than 10 characters long"
                },
                subject: "Please enter subject",
                message: "Please enter your message"
            },
            submitHandler: function (form) {
                form.submit();
            }
        });
    }); 
</script>

Contact Form Validation with jQuery

Database Connection

To make the database connection, place the following code in the config/database.php file.

<?php

    $hostname = "localhost";
    $username = "root";
    $password = "";

    try {
        $connection = new PDO("mysql:host=$hostname;dbname=php_crud", $username, $password);
        $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch(PDOException $e) {
        echo "Database connection failed: " . $e->getMessage();
    }

?>

Create Contact Form Table

Execute sql command to create the table structure for database table `contacts_list`. We will use the following table to store the contact form data.

CREATE TABLE `contacts_list` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  `email` varchar(100) NOT NULL,
  `phone` varchar(50) NOT NULL,
  `subject` varchar(255) NOT NULL,
  `Message` text NOT NULL,
  `sent_date` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

PHP Contact Form Example

Use $_POST to post contact form values, to receive user information set the recipient mail and pass the user information in the mail function.

<?php
    include('config/database.php');

    if(!empty($_POST["send"])) {
    $name = $_POST["name"];
    $email = $_POST["email"];
    $phone = $_POST["phone"];
    $subject = $_POST["subject"];
    $message = $_POST["message"];

    // Recipient email
    $toMail = "johndoe@gmail.com";
    
    // Build email header
    $header = "From: " . $name . "<". $email .">\r\n";

    // Send email
    if(mail($toMail, $subject, $message, $header)) {

        // Store contactor data in database
        $sql = $connection->query("INSERT INTO contacts_list(name, email, phone, subject, message, sent_date)
        VALUES ('{$name}', '{$email}', '{$phone}', '{$subject}', '{$message}', now())");

        if(!$sql) {
            die("MySQL query failed.");
        } else {
            $response = array(
            "status" => "alert-success",
            "message" => "We have received your query and stored your information. We will contact you shortly."
            );              
        }
    } else {
        $response = array(
            "status" => "alert-danger",
            "message" => "Message coudn't be sent, try again"
        );
    }
    }  
?>

When mail is received, we are using the SQL query to store the contact form data into the database. Display success or error message based on the response.

store the contact form data into the database

The Final Code

We have connected every element of our contact form now the final code looks like this.

<!doctype html>
<html>

<head>
  <meta charset="utf-8">
  <title>Contact Form in PHP</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
  <style>
    .container {
      max-width: 500px;
      margin: 50px auto;
      text-align: left;
      font-family: sans-serif;
    }

    form {
      border: 1px solid #1A33FF;
      background: #ecf5fc;
      padding: 40px 50px 45px;
    }

    .form-control:focus {
      border-color: #000;
      box-shadow: none;
    }

    label {
      font-weight: 600;
    }
    
    .error {
      color: red;
      font-weight: 400;
      display: block;
      padding: 6px 0;
      font-size: 14px;
    }

    .form-control.error {
      border-color: red;
      padding: .375rem .75rem;
    }    
  </style>
</head>

<body>

  <div class="container mt-5">
    
    <?php
      include('config/database.php');

      if(!empty($_POST["send"])) {
        $name = $_POST["name"];
        $email = $_POST["email"];
        $phone = $_POST["phone"];
        $subject = $_POST["subject"];
        $message = $_POST["message"];

        // Recipient email
        $toMail = "digamber@positronx.io";
        
        // Build email header
        $header = "From: " . $name . "<". $email .">\r\n";

        // Send email
        if(mail($toMail, $subject, $message, $header)) {

            // Store contactor data in database
            $sql = $connection->query("INSERT INTO contacts_list(name, email, phone, subject, message, sent_date)
            VALUES ('{$name}', '{$email}', '{$phone}', '{$subject}', '{$message}', now())");

            if(!$sql) {
              die("MySQL query failed.");
            } else {
              $response = array(
                "status" => "alert-success",
                "message" => "We have received your query and stored your information. We will contact you shortly."
              );              
            }
        } else {
            $response = array(
                "status" => "alert-danger",
                "message" => "Message coudn't be sent, try again"
            );
        }
      }  
    ?>

    <!-- Messge -->
    <?php if(!empty($response)) {?>
      <div class="alert text-center <?php echo $response['status']; ?>" role="alert">
        <?php echo $response['message']; ?>
      </div>
    <?php }?>

    <!-- Contact form -->
    <form action="" name="contactForm" method="post" enctype="multipart/form-data">
      <div class="form-group">
        <label>Name</label>
        <input type="text" class="form-control" name="name" id="name">
      </div>

      <div class="form-group">
        <label>Email</label>
        <input type="email" class="form-control" name="email" id="email">
      </div>

      <div class="form-group">
        <label>Phone</label>
        <input type="text" class="form-control" name="phone" id="phone">
      </div>

      <div class="form-group">
        <label>Subject</label>
        <input type="text" class="form-control" name="subject" id="subject">
      </div>

      <div class="form-group">
        <label>Message</label>
        <textarea class="form-control" name="message" id="message" rows="4"></textarea>
      </div>

      <input type="submit" name="send" value="Send" class="btn btn-dark btn-block">
    </form>
  </div>

  <!-- JavaScript -->
  <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.2/dist/jquery.validate.min.js"></script>
  
  <script>
    $(function() {
      $("form[name='contactForm']").validate({
        // Define validation rules
        rules: {
          name: "required",
          email: "required",
          phone: "required",
          subject: "required",
          message: "required",
          name: {
            required: true
          },
          email: {
            required: true,
            email: true
          },          
          phone: {
            required: true,
            minlength: 10,
            maxlength: 10,
            number: true
          },          
          subject: {
            required: true
          },          
          message: {
            required: true
          }
        },
        // Specify validation error messages
        messages: {
          name: "Please provide a valid name.",
          email: {
            required: "Please enter your email",
            minlength: "Please enter a valid email address"
          },
          phone: {
            required: "Please provide a phone number",
            minlength: "Phone number must be min 10 characters long",
            maxlength: "Phone number must not be more than 10 characters long"
          },
          subject: "Please enter subject",
          message: "Please enter your message"
        },
        submitHandler: function(form) {
          form.submit();
        }
      });
    });    
  </script>

</body>

</html>

Conclusion

So this was it. Finally, we have learned how to create a PHP contact form from scratch.

Get the complete code of this tutorial on GitHub.