Last Updated on March 5, 2023 by Roshan Parihar
In this post, learn about the PHP contact form and the script for validation and send emails with form data. You will also get PHP code to insert data into the database and display it on your website pages.
If you are running an online business, a contact form can be the best solution for you to collect user queries from your website. You can add contact forms to your website contact page.
Looking to create contact forms without coding? Create beautiful looking contact forms with JotForm.
Each time when your users want to contact you, they will visit to contact us page and fill out the contact form to send their queries. After collecting queries from your users, you can start further communication to convert them into regular customers.
You can easily create a contact form and send data in emails using PHP. The contact form sends emails only after getting valid entries from users. It also inserts data into the database after all the user’s input data are correct and valid.
So, let’s get started.
PHP Contact Form Appearance
The contact form should contain all the necessary fields to easily collect users’ data with queries. It also contains an email or phone number to contact the users for communication.
Longer size contact form is difficult for users to fill in data. That way, to make the contact form as simple as possible I have added only three form fields that are given below:-
- Name
- Message
The above fields are enough to easily collect queries and contact your users with an answer to their queries. The HTML code for the contact form is given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<div class="main-contact-form"> <form action="#" method="POST"> <label for="Name">Your Name</label> <input type="text" name="name" class="name" placeholder="Enter name" required> <label for="Email">Your Email</label> <input type="email" name="email" class="email" placeholder="Enter email" required> <label for="message">Message</label> <textarea name="message" class="message" placeholder="Enter your message" rows="5" required></textarea> <input name="submit" type="submit" value="Submit"> </form> </div> |
The appearance of the contact is shown below. The interface not looks good and to make it beautiful, you have to add some CSS for styling
To add styling to your contact form, you have to add some CSS given below. It styles all the input fields, text area, and the submit button. You can change the submit button color as per your website color.
Add Style to Contact Form
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
<style> input[type='text'],input[type='email'], textarea{ width: 100%; padding: 10px; border-radius: 3px; border: 1px solid #ccc; margin-top: 10px; margin-bottom: 20px; } input[type='text']:focus,input[type='email']:focus, textarea:focus{ border: 1px solid #5db6db; box-shadow: 0 0 10px #b9eaff; outline: none !important; } input[type='submit']{ background: rgb(39,160,210); color: #fff; border: none; padding: 10px 20px; cursor: pointer; } .main-contact-form{ max-width: 400px; margin: 0 auto; background: #e9e9e9; padding: 20px 45px 20px 25px; border-radius: 5px; } </style> |
After adding styling to your contact form, your form appearance will look like the image below. The interface looks good to add to your website and display to your users. It is responsive to easily display in any size device like desktop, laptop, tablet, and mobile.
Now, let’s add some validation to your contact form to collect valid data from users. After that, you can use the code below to send an email that contains the users entered data.
PHP Contact Form Add Validation and Send Data in Emails
HTML input fields come with the default attribute required
that you can add to your input fields to make it required. The only validation here which is required is email format.
The below example code matches the email regex expression with the user input email address to find the valid email address. If the email address is not valid, it displays error messages. When the user enters a valid email address, it executes the next PHP code to send the email address.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
<?php if(isset($_POST['submit'])){ //Get form data $name = $_POST['name']; $email = $_POST['email']; $message = $_POST['message']; $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/'; if (!preg_match($email_exp, $email)) { echo '<br><span style="color:red;">The Email address you entered is not valid.</span>'; exit; } $subject = "Contact Form"; //Subject of the email //Message content to send in an email $message = "Name: ".$name."<br>Email: ".$email."<br> Message".$message; //Email headers $headers = "From:".$email."\r\n"; $headers .= "Reply-To:".$email."\r\n"; $headers .= "X-Mailer: PHP/".phpversion(); //Send email mail($to, $subject, $message, $headers); } ?> |
Now, next is to insert the data into the database and display it on a page. Let’s do this in the next section.
Insert Form Data Into Database and Display in a Page
After you insert the data into the database, you can display the data somewhere on your website page. It is useful when you want to find the user’s email address to start communication with them in the future.
You have to first create a database in your PHPMyadmin.
login to PHPMyAdmin
After that, open the ‘SQL’ tab there.
Open the ‘SQL’ tab of PHPMyAdmin
Create a database to insert PHP contact form data
Now, copy the below code and add it to the input area given in the ‘SQL’ tab. After that, press the ‘Go’ button to execute the below SQL code and create the database with the name ‘contact_form’.
It also creates the table ‘contacts’ with the creation of the database ‘contact_form’.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
-- -- Database: `contact_form` -- CREATE DATABASE IF NOT EXISTS `contact_form` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci; USE `contact_form`; -- -- Table structure for table `contacts` -- CREATE TABLE `contacts` ( `id` bigint(60) NOT NULL, `name` varchar(100) NOT NULL, `email` varchar(100) NOT NULL, `message` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Indexes for table `contacts` -- ALTER TABLE `contacts` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for table `contacts` -- ALTER TABLE `contacts` MODIFY `id` bigint(60) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1; |
Connect to Your Database Using PHP
After you create the database, you can connect to the database using the PHP code given below. The code requires the server name, the username of the database, and the password of the database user.
The code also checks the connection to show a success message when the connection is made successfully.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?php //Make database connection $servername = "localhost"; $username = "root"; $password = ""; $dbname = "contact_form"; // Create a connection $conn = mysqli_connect($servername, $username, $password, $dbname); // Check the connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); }else{ echo "connected successfully"; } ?> |
Insert Contact Form Data Into the Database
To insert the contact form data into your created database, you have to use the PHP code given below. The code for the PHP contact form inserts the data into the database and displays the success message after insertion.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?php if(isset($_POST['submit'])){ $sql = "INSERT INTO contacts (name, email, message) VALUES ('$name', '$email', '$message')"; if (mysqli_query($conn, $sql)) { echo "New contact added successfully"; } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); } mysqli_close($conn); } ?> |
Now, you have successfully sent the email and inserted the form data into the database. It’s time to display the data on your website page to make it easier for the website owner to keep a record of users.
Display Inserted Data in a Table
For the below PHP code first, select the table ‘contacts’ and check whether it contains user records or not. After that, it displays all the data in a table using a loop in PHP.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
<?php $sql = "SELECT * FROM contacts"; $result = mysqli_query($conn, $sql); $i = 1; if (mysqli_num_rows($result) > 0) { ?> <table class="table table-bordered table-hover table-striped"> <tr> <th>Sr. No.</th> <th>Name</th> <th>Email</th> <th>Message</th> </tr> <?php while ($row = mysqli_fetch_assoc($result)) { ?> <tr> <td><?php echo $i; ?></td> <td><?php echo $row['name']; ?></td> <td><?php echo $row['email']; ?></td> <td><?php echo $row['message']; ?></td> </tr> <?php } ?> </table> <?php } ?> |
You will get the user’s data in the table format on your website. To make your table looks better on your website, you can also add some style given below.
1 2 3 4 5 6 7 8 9 10 |
<style> table{ border-collapse: collapse; margin: 20px auto; } table, td, th { border: 1px solid #ccc; padding: 10px; } </style> |
You May Also Like to Read