PHP Contact Us Form with Validation

In this tutorial, you will learn how to create a contact form in PHP and submit the contact us form data to the MySQL database with jQuery validation.

Contact us Form PHP with jQuery Validation

Here are steps:

Step 1 – Create Table in Database

First of all, go to your PHPMyAdmin and create a table name contacts_list with the following fields: name, email, mobile.

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;

Step 2 – Create a Database Connection File

In this step, you will create a file name db.php and update the below code into your file.

The below code is used to create a MySQL database connection in PHP. When we insert form data into MySQL database, there we will include this file:

<?php
	$servername='localhost';
	$username='root';
	$password='';
	$dbname = "my_db";
	$conn=mysqli_connect($servername,$username,$password,"$dbname");
	  if(!$conn){
		  die('Could not Connect MySql Server:' .mysql_error());
		}
?>

Step 3 – Create a Contact Form in PHP

In this step, you need to create a contact form and add the the following code into your contact-form.php file:

<!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('db.php');
if(!empty($_POST["send"])) {
$name = $_POST["name"];
$email = $_POST["email"];
$phone = $_POST["phone"];
$subject = $_POST["subject"];
$message = $_POST["message"];
// Recipient email
$toMail = "[email protected]";

// 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>

</body>
</html>

Step 4 – Add jQuery Validation

Edit contact-form.php file, and add jquery validation in it:

  <!-- JavaScript -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/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>

Conclusion

In this tutorial, you have learned how to create contact form with jQuery validation and store data into a MySQL database.

Recommended PHP Tutorials

If you have any questions or thoughts to share, use the comment form below to reach us.

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

Your email address will not be published. Required fields are marked *