Key Takeaways
- A PHP contact form uses HTML for the front-end structure, PHP for server-side processing, and MySQL to store submissions.
- Use POST method instead of GET to keep submitted data hidden from the browser URL.
- AJAX submission with jQuery prevents page reloads and provides a better user experience.
- CAPTCHA using PHP’s GD library blocks bot submissions without requiring third-party services.
A PHP contact form allows users to communicate with website administrators. It allows them to send queries to the site owners about relevant services or features. Using the contact form, web administrators are able to manage their business emails. Once there is an active contact form available, it can generate queries. It easily gets connected with the database, thus providing complete records and details about the users who are willing to contact and send their queries to website administrators.
Prerequisites
To create a simple PHP contact form with MySQL, I assume that you have a PHP application installed on a web server. My setup is:
- PHP 7.1
- MySQL
- Jquery/Ajax
To make sure that that I don’t get side-tracked by server level issues, I decided to host PHP application on Cloudways managed servers because the platform offers a powerful PHP optimized environment. In addition, I don’t have to deal with server management hassles and thus focus on the core idea of this tutorial.
You can also try out Cloudways for free by signing up an account on the platform following this GIF:

Create the Contact Form HTML
Create the contact form HTML as shown below with 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 . 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. If you don’t have the time to dive deep in technicalities, you can use online forms that are pre-designed according to professional form design standards.
Note: For styling you can use your own CSS and also use Bootstrap Classes for better styling.
!DOCTYPE html>
<html>
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<style>
#loading-img{
display:none;
}
.response_msg{
margin-top:10px;
font-size:13px;
background:#E5D669;
color:#ffffff;
width:250px;
padding:3px;
display:none;
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-8">
<h1><img src="Inquiry.png" width="80px">Easy Contact Form With Ajax MySQL</h1>
<form name="contact-form" action="" method="post" id="contact-form">
<div class="form-group">
<label for="Name">Name</label>
<input type="text" class="form-control" name="your_name" placeholder="Name" required>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" name="your_email" placeholder="Email" required>
</div>
<div class="form-group">
<label for="Phone">Phone</label>
<input type="text" class="form-control" name="your_phone" placeholder="Phone" required>
</div>
<div class="form-group">
<label for="comments">Comments</label>
<textarea name="comments" class="form-control" rows="3" cols="28" rows="5" placeholder="Comments"></textarea>
</div>
<button type="submit" class="btn btn-primary" name="submit" value="Submit" id="submit_form">Submit</button>
<img src="img/loading.gif" id="loading-img">
</form>
<div class="response_msg"></div>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#contact-form").on("submit",function(e){
e.preventDefault();
if($("#contact-form [name='your_name']").val() === '')
{
$("#contact-form [name='your_name']").css("border","1px solid red");
}
else if ($("#contact-form [name='your_email']").val() === '')
{
$("#contact-form [name='your_email']").css("border","1px solid red");
}
else
{
$("#loading-img").css("display","block");
var sendData = $( this ).serialize();
$.ajax({
type: "POST",
url: "get_response.php",
data: sendData,
success: function(data){
$("#loading-img").css("display","none");
$(".response_msg").text(data);
$(".response_msg").slideDown().fadeOut(3000);
$("#contact-form").find("input[type=text], input[type=email], textarea").val("");
}
});
}
});
$("#contact-form input").blur(function(){
var checkValue = $(this).val();
if(checkValue != '')
{
$(this).css("border","1px solid #eeeeee");
}
});
});
</script>
</body>
</html>
Configure the MySQL Database
The next step is to setup and configure the MySQL database. For this, fire up the Cloudways Database manager and create a table ‘contact_form_info’, with the fields id , name , email , phone,comments.
Next, create config.php that will be used to set up the connection between the PHP app and the database. Once the file has been created, open it and paste the following code in it:
<?php
$host = "localhost";
$userName = "fyrhp";
$password = "RTDE";
$dbName = "fyrhp";
// Create database connection
$conn = new mysqli($host, $userName, $password, $dbName);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
You might also like: How to Connect to a Remote MySQL Database
Create the PHP Contact Form Script
Now let’s create a file get_response.php and paste the following code in it:
<?php
require_once("config.php");
if((isset($_POST['your_name'])&& $_POST['your_name'] !='') && (isset($_POST['your_email'])&& $_POST['your_email'] !=''))
{
require_once("contact_mail.php");
$yourName = $conn->real_escape_string($_POST['your_name']);
$yourEmail = $conn->real_escape_string($_POST['your_email']);
$yourPhone = $conn->real_escape_string($_POST['your_phone']);
$comments = $conn->real_escape_string($_POST['comments']);
$sql="INSERT INTO contact_form_info (name, email, phone, comments) VALUES ('".$yourName."','".$yourEmail."', '".$yourPhone."', '".$comments."')";
if(!$result = $conn->query($sql)){
die('There was an error running the query [' . $conn->error . ']');
}
else
{
echo "Thank you! We will contact you soon";
}
}
else
{
echo "Please fill Name and Email";
}
?>
In this PHP code, I have used the POST method for submitting the contact form data to the server. I will use two PHP global methods, $_REQUEST and $_POST to retrieve and save the contact form data in the server local variable.
The difference between these two is that $_REQUEST can retrieve data from both methods i.e. GET and POST. However, $_POST can only receive data from the POST method.
Here is what the PHP contact form script looks in action:

Mail Method
I also create a file contact_mail.php for mail in which send your contact form data on your mail easily.
<?php $toEmail = "[email protected]"; $mailHeaders = "From: " . $_POST["your_name"] . "<". $_POST["your_email"] .">\r\n"; if(mail($toEmail, $_POST["comments"], $_POST["your_phone"], $mailHeaders)) { echo"<p class='success'>Contact Mail Sent.</p>"; } else { echo"<p class='Error'>Problem in Sending Mail.</p>"; } ?>
You might also like: How to Send Email in PHP
Form Captcha
You can use Captcha code in a form to ensure that the form is submitted with manual intervention without using any tools.
PHP Contact Form with Captcha
To develop contact form with captcha, let’s start with the following HTML code. In this code, I will put a PHP file link into the image tag with the name of captcha.php.
<div> <label>Captcha</label> <span id="captcha-info" class="info"></span><br/> <input type="text" name="captcha" id="captcha" class="demoInputBox"><br> </div> <div> <img id="captcha_code" src="captcha.php" /> <button name="submit" class="btnRefresh" onClick="refreshCaptcha();">Refresh Captcha</button> </div>
Contact Form Captcha Validation
For Captcha field validation, you can paste the following code in <script> tag. Using this code, you can set jQuery validation for captcha form validation.
if(!$("#captcha").val()) {
$("#captcha-info").html("(required)");
$("#captcha").css('background-color','#FFFFDF');
valid = false;
}
Captcha Refresh
This simple jQuery script will refresh PHP captcha code, and recreate the image with the new code. This new image will be set as captcha image source.
function refreshCaptcha() {
$("#captcha_code").attr('src','captcha.php');
}
PHP Captcha Image
PHP uses a function called PHP rand() to generate a random number. Using md5(), you can encrypt the number and split it into 6-character captcha code. The code is not only added to the PHP session but also added as a source of captcha image using PHP GD function.
session_start();
$random_alpha = md5(rand());
$captcha_code = substr($random_alpha, 0, 6);
$_SESSION["captcha_code"] = $captcha_code;
$target_layer = imagecreatetruecolor(70,30);
$captcha_background = imagecolorallocate($target_layer, 255, 160, 119);
imagefill($target_layer,0,0,$captcha_background);
$captcha_text_color = imagecolorallocate($target_layer, 0, 0, 0);
imagestring($target_layer, 5, 5, 5, $captcha_code, $captcha_text_color);
header("Content-type: image/jpeg");
imagejpeg($target_layer);
Form Handler Library
You can also perform captcha and form validation by using Form Handler library. Check the following example:
use FormGuide\Handlx\FormHandler;
$demo = new FormHandler();
$validator = $demo->getValidator();
$validator->fields(['name','email'])->areRequired()->maxLength(50);
$validator->field('email')->isEmail();
$validator->field('message')->maxLength(6000)
$demo->requireCaptcha();
Supercharged Managed PHP Hosting – Improve Your PHP App Speed by 300%
Final Words
A complete PHP contact form requires five components working together: the HTML form with client-side validation, a PHP processing script that sanitizes and stores submissions, a MySQL database to retain submission records, an email notification handler, and CAPTCHA to block bot submissions.
Here is a quick reference for the files created in this guide:
| File | Purpose |
|---|---|
index.php (or contact.php) |
HTML form with jQuery and AJAX submission |
config.php |
MySQL database connection |
get_response.php |
Server-side validation, database insert, and response |
contact_mail.php |
Email notification to site administrator |
captcha.php |
GD-generated CAPTCHA image |
Once all five files are in place and connected, the form collects user submissions, stores them in the database, notifies you by email, and blocks automated bot traffic through CAPTCHA validation.
Still, if you have some more questions regarding captcha integration in the contact form, or want to share some of your tips on the topic, feel free to write down your suggestions in the comments section below.
Q. How Do I Create a PHP Contact Form?
A. Create an HTML form with POST method, write a PHP script to validate and process the submitted data using $_POST, insert the data into MySQL with sanitized values, and send an email notification using mail() or PHPMailer.
Q. Do I Need PHP for a Contact Form?
A. PHP is the standard server-side language for processing contact form submissions, validating input, and sending email. Alternatives include JavaScript with a backend API or third-party form services, but PHP remains the most common choice for self-hosted solutions.
Q. What is the Difference Between GET and POST for Contact Forms?
A. POST keeps submitted data out of the browser URL and has no size limit on the amount of data it can send. GET appends form data to the URL and is limited in length. Contact forms should always use POST to protect user data and avoid submission data appearing in server logs.
Q. How Do I Prevent Spam in a PHP Contact Form?
A. Add CAPTCHA using PHP’s GD library or a service like reCAPTCHA. You can also use honeypot fields (hidden form fields that bots fill in but humans do not), rate limiting, server-side input validation, and form token verification to block automated submissions.
Q. How Do I Send an Email From a PHP Contact Form?
A. Use PHP’s built-in mail() function for basic email sending, passing the recipient address, subject, message body, and headers. For better reliability and spam filter avoidance, use PHPMailer with SMTP authentication instead of the native mail() function.
Q. How Do I Store PHP Contact Form Submissions in MySQL?
A. Connect to MySQL using mysqli or PDO, sanitize the submitted values using real_escape_string() or prepared statements, then run an INSERT query to save the data to your submissions table. Retrieve stored submissions later using SELECT queries in phpMyAdmin or your admin panel.
Q. Why is My PHP Contact Form Going to Spam?
A. The most common reasons are missing or improperly formatted email headers, using a no-reply address that does not match your domain, or using PHP’s basic mail() function without SMTP authentication. Configure SPF and DKIM records for your domain and switch to PHPMailer with SMTP to improve deliverability.
Salwa Mujtaba
Salwa Mujtaba is a Technical Content Writer at Cloudways. With a strong background in Computer Science and prior experience as a team lead in Cloudways Operations, she brings a deep understanding of the Cloudways Platform to her writing. Salwa creates content that simplifies complex concepts, making them accessible and engaging for readers. When she's not writing, you can find her enjoying good music, reading a book, or spending quality time with her family.