Last Updated on January 22, 2023 by Roshan Parihar
In this post, learn how to create a dynamic contact form in PHP with MySQL. You can add custom dynamic fields to forms to process their data dynamically.
When you want to capture dynamic data of your audience, you can add dynamically created fields to your contact form. It allows customers to add more custom input fields on button clicks.
Looking to create dynamic contact forms and send emails with data display without coding? Create beautiful-looking contact forms with JotForm.
The customers can fill in the dynamic input fields and you can either collect it via emails or store it in the database. After that, you can make one-to-one communicate with them to solve their queries.
For example, if your customers have some queries regarding multiple products on your website. You can allow customers to enter queries and enter multiple products name using dynamic fields. This shows how much useful it is for businesses.
I am going to show you how to add and remove dynamic input fields to your contact form with a button click. You will also learn how to send the dynamic field data in emails and store it in the MySQL database.
So, let’s get started.
How to Create a Dynamic Contact Form in PHP with MySQL
Here is the step-by-step process to easily create a dynamic contact form in PHP and MySQL:-
Step 1: Create Dynamic Contact Form Design
Firstly, you have to create a beautifully designed contact form with form fields to collect user information. The form fields should collect all the information required to make efficient communication with your audience.
The following fields are an important part of the contact form to collect users information useful for one-to-one communication:-
- Name
- Message
- Dynamic Field with ‘Add more’ input button
Below is the simple code of the contact form containing a dynamic field with Name, Email, and Message text area.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<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> <label for="Dynamic Field">Dynamic Field</label> <input type="text" name="dynamic_field[]" placeholder="Enter product name"> <div id="newRow"> </div><br> <button id="addRow" type="button" class="btn btn-info">Add More</button> <input name="submit" type="submit" value="Submit"> </form> </div> |
To make it look beautiful on your website, let’s add some CSS for the styling of the contact form with the code below.
Styling Dynamic 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 30 31 32 33 34 |
<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; } #inputFormRow input[type='text']{ width: auto !important; margin-top: 2px; margin-bottom: 2px; } 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'], button{ 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> |
Now, you have added a simple contact form and made it beautiful by adding some CSS code to it. When you see the above code on your browser, the appearance of your contact form will look like the image below.
The above image shows that the form contains fields Name, Email, and Message. It also contains a dynamic field with the add button to add more input fields to your contact form dynamically. You can also delete the dynamically added input field using the remove button.
Step 2: jQuery Script to Add Dynamic Fields to Contact Form
To make the above ‘Add More’ and ‘Remove’ button work to add/remove dynamic input fields on your contact form, you have to add some jQuery script given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<script type="text/javascript"> // add row $("#addRow").click(function () { //i++; var html = ''; html += '<div id="inputFormRow">'; html += '<input type="text" name="dynamic_field[]" placeholder="Enter product name">'; html += '<button id="removeRow" type="button">Remove</button>'; html += '</div>'; $('#newRow').append(html); }); // remove row $(document).on('click', '#removeRow', function () { $(this).closest('#inputFormRow').remove(); }); </script> |
Now, your form design is completed with a feature to add/remove dynamic input fields on your contact form.
The next step is to add some PHP code to collect your customer’s data in the dynamic contact form and send it in an email to the website owner. So, let’s move further to do this.
Step 3: Send Dynamic Contact Form Data in Email Using PHP
To send dynamic contact form data in email using PHP, see the PHP code given below. It first collects the form data for the Name, Email, and Message using $_POST
global variable. After that, validate the email address to find out whether the email address is correct or not.
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 31 32 33 34 35 36 37 38 39 |
<?php if(isset($_POST['submit'])){ //Get form data $name = $_POST['name']; $email = $_POST['email']; $message = $_POST['message']; //validation for email $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."<br>"; //Include dynamic content in email message content $message .= "Dynamic field details:"; foreach ($_POST["dynamic_field"] as $key => $value) { if($value !== ''){ $message .= $value.","; } } //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); } ?> |
Let’s understand each variable to send emails using PHP code:-
$to
: It is the recipient’s email address which is the email address of the website owner.$subject
: The subject of the email.$message
: The main content of the email to send to the recipient. You can add the captured data of the contact form which are Name, Email, Message, and the Dynamic Field of the contact form.$key
: It is the index position of the dynamic values.$value
: It is the main value of the dynamic field.$headers
:- ‘From’ is the email address of the website owner that should be domain specific.
- ‘CC’ is the email address of the other person who wants to receive the email.
- “Reply-To’ is the email address of your customer who fills out the contact form.
mail()
: It is the in-built function in PHP to send emails. It requires 4 variables to pass as an argument of the function to make it work in PHP.
Now, you have sent an email to the website owner.
But, how you can find your customer’s data in the future when you want to make one-to-one communication with them? One best solutions is the store your contact form data in MySQL data and display it somewhere on your website page. This way, you can easily find your customer data when required.
So, let’s insert contact form data with the dynamic field into the database and display it on a website page using PHP and MySQL.
Step 4: Insert Dynamically Created Data Using PHP and MySQL
You have to first create a MySQL database and table inside it to insert your contact form data into it using PHP. The table should contain columns for all the contact form fields which are Name, Email, Message, and Dynamic Field.
Let’s take an example of creating a database with the name ‘contact_form‘ and table ‘contacts‘ inside it with all columns as form fields. Now, let’s move ahead to create the database with the table.
Create MySQL Database to Store Records
To create the database and a table inside it, you have to first log in to your PHPMyadmin. Open PHPMyAdmin and enter your username and password to log in.
After that, open the SQL tab as indicated in the image below. The SQL tab contains the feature to run the SQL code to create the database and table in it.
You will get a large input text area in the ‘SQL’ tab where you have to copy and paste the below code.
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 |
-- -- 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, `dynamic_field` 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; |
After that, click ‘Go’ to execute your SQL code to create your database with a table to store data in columns.
Now, your database is ready to store records. So, let’s insert some data into it.
But, before you insert data into your database, you have to make a connection with your data. Without making a connection with your database using PHP, you won’t be able to insert dynamic contact form data into it.
So, let’s first make a connection with your database using PHP.
Make MySQL Database Connection
To make connecting with your database, you have to use the below code. It contains the PHP mysqli_connect()
that requires 4 arguments that are server name, the username of your database, the password of your database, and your database name.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?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"; } ?> |
Now, you have successfully made a connection with your database, you can now capture contact form data and insert it into your database. So, let’s do this.
Insert Data Into MySQL Database with Dynamic Fields
To insert dynamic contact form data into the database, you have to first get the customers entered form data using $_POST
global variable.
But, how you can collect dynamic field data of your dynamic contact form? Well! it’s simple when you use an associative array to store it into an array variable.
You can create an array of multiple dynamic input fields with all of the same name. When you check the dynamic contact form design given above, you will get the same name for all dynamically added input fields.
To create an array of multiple dynamic input fields, you have to use the for
loop of PHP as given in the below PHP code.
As you cannot be able to insert an array directly into the MySQL database. So, after creating an array of dynamic field data, you have to convert it into a string using serialize()
function of PHP. . That’s why converting the array into a string makes it easier to insert it into the database.
After that, you can create an insert SQL in PHP as given in the code below. To execute the query and insert the data into the database, you have to use the mysqli_query()
and pass the connection variable and query variable as their first and second argument.
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 31 32 33 34 35 36 37 38 |
<?php if(isset($_POST['submit'])){ //Get form data $name = $_POST['name']; $email = $_POST['email']; $message = $_POST['message']; $dynamic_field = $_POST["dynamic_field"]; //validation for email $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; } //Store dynamic fields in an associative array $dynamic_field_array = []; for ($i = 0; $i < count($_POST["dynamic_field"]); $i++) { $dynamic_field_array[$i] = [ 'name'=>$dynamic_field[$i] ]; } //Convert dynamic field array into a string to store in database $dynamic_field_array_string = serialize($dynamic_field_array); //Insert dynamic field into the database $sql = "INSERT INTO contacts (name, email, message, dynamic_field) VALUES ('$name', '$email', '$message', '$dynamic_field_array_string')"; if (mysqli_query($conn, $sql)) { echo "New contact added successfully"; } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); } } ?> |
Now, you have successfully inserted the dynamic contact form data into your database. Let’s display the data somewhere on your website page.
Step 5: Display Records in a Table Using PHP and MySQL
To display the dynamic contact form data on your website page, you have to first select the table of the database. As the table name is ‘contacts’, you have to create the ‘select’ SQL query and store it in a variable. After that, execute the query using the mysqli_query()
function of PHP.
If you want to display the data only when the database contains some records available in it, you have to use the mysqli_num_rows()
as given below.
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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
<?php $sql = "SELECT * FROM contacts"; $result = mysqli_query($conn, $sql); $i = 1; if (mysqli_num_rows($result) > 0) { ?> <style> table{ border-collapse: collapse; margin: 20px auto; } table, td, th { border: 1px solid #ccc; padding: 10px; } </style> <table class="table table-bordered table-hover table-striped"> <tr> <th>Sr. No.</th> <th>Name</th> <th>Email</th> <th>Message</th> <th>Products (Dynamic Field)</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> <td> <?php $dynamic_field_array_string_unserialize = unserialize($row['dynamic_field']); foreach ($dynamic_field_array_string_unserialize as $key) { echo $key['name'].", "; } ?> </td> </tr> <?php $i++; } ?> </table> <?php } mysqli_close($conn); ?> |
For displaying the dynamic fields, you have to first convert the dynamic string into an array using the unserialize()
function of PHP. After that, use the foreach()
function of PHP to display each dynamic field data one by one.
The output of the above code is as showing in the table below in the image.
The table contains the columns with names as the input fields of the dynamic contact form. It also contains the customers entered example data. The dynamically added field data are shown in comma(,) separation for each entry.
That’s all.