By request, let’s build a simple Contact Form with a PHP/MySQL backend!
(Disclaimer: I don’t pretend to be an expert in PHP [nor .NET for that matter!], so please understand that the way I go about this might be sub-optimal. Whatever, sue me.)
Building the HTML Contact Form
This part is as straightforward as can be. We’re going to create a ‘Contact Form’ with a grand total of THREE fields – extending this model is left as an exercise for the reader (lol, always wanted to write that!)
For brevity, we’re going to use the HTML5 doctype and a table-based (gasp!) layout. Feel free to change it to whatever you want.
Here goes:
<!DOCTYPE html>
<html>
<head>
<title>My Rad Contact Form</title>
<style type="text/css">
table tr > td { text-align: right; }
table tr > td + td { text-align: left; }
</style>
</head>
<body>
<form action="ContactFormHandler.php" method="post">
<table>
<tr>
<td>
Your Name:
</td>
<td>
<input type="text" id="Name" name="Name" />
</td>
</tr>
<tr>
<td>
Your Email:
</td>
<td>
<input type="text" id="Email" name="Email" />
</td>
</tr>
<tr>
<td>
Least Favorite Color:
</td>
<td>
<select id="LeastFavoriteColor" name="LeastFavoriteColor">
<option value="">- Choose -</option>
<option value="Blue">Blue</option>
<option value="Green">Green</option>
<option value="Orange">Orange</option>
<option value="Red">Red</option>
<option value="Yellow">Yellow</option>
</select>
</td>
</tr>
<tr>
<td colspan="2" style="text-align: center;">
<input type="submit" id="submit" value="Contact Me!" />
<input type="reset" id="reset" value="Start Over!" />
</td>
</tr>
</table>
</form>
</body>
</html>
Which, in IE9 renders as:

I’ve highlighted line 10 above to bring attention to the ‘action’ attribute of our opening form element. Whatever the form’s action is set to is where, on submission, the form ‘posts’ its values to. To read more about HTTP POST, please visit google.
And that completes the form!
Creating a MySQL Table to Store Form Values
Again, as a Microsoft fanboy ©, I rarely spend much time with MySQL in any real capacity. You have been warned.
We are going to assume that you have a MySQL instance installed and available to you. And that you know how to login and arrive at the MySQL ‘command line.’
Once logged in, we’ll first need to create a new database to store our new table which in turn will store our contact form values:
mysql> CREATE DATABASE MyRadContactForm;
Not surprisingly, this creates a new database with the name MyRadContactForm. The ALL CAPS is not required, but SQL is typically written in this fashion.
Next, we must let MySQL know what database we want to use:
mysql> USE MyRadContactForm;
Now our new DB is the active one, and we can create our table in it:
mysql> CREATE TABLE MyRadContacts (
-> ContactID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> ContactName VARCHAR(100),
-> ContactEmail VARCHAR(100),
-> ContactLeastFavoriteColor VARCHAR(10)
-> ContactDateCreated DATETIME
-> );
Quickly, ContactID is what we call a Primary Key – it is used to uniquely identify each record in the table.
It is an INT (Integer) type, meaning it can store whole numbers.
It is a NOT NULL column, meaning that it must contain a value for each row in the table.
And finally, it is an AUTO_INCREMENT column – this means that each time we add a new record to this table, MySQL will ensure that each ID is unique by essentially adding one to the highest existing ID at the time of a new insert.
VARCHAR(100) means that we can store a string (sequence of letters, numbers, etc) up to 100 characters in length.
DATETIME… well, that should be obvious.
Our new table should now be in place, though to quickly check, we can try:
mysql> SHOW TABLES; +----------------------------+ | Tables in MyRadContactForm | +----------------------------+ | MyRadContacts | +----------------------------+
Creating PHP Server-Side Code to Store New Values
Well, now we have something the client sees (the HTML form) and something buried deep within the bowels of a database to store values input by the client.
How, then, do we manage to bridge the gap between these two pieces?
In this case, we’ll use PHP.
We assume that you have a functioning PHP installation. Check out xampp for a relatively painless way to get up and running with PHP/MySQL/Apache on various platforms.
Right, without further delay:
<?php
// Grab our POSTed form values
// Note that whatever is enclosed by $_POST[""] matches the form input elements
$contactName = $_POST["ContactName"];
$contactEmail = $_POST["ContactEmail"];
$contactLeastFavoriteColor = $_POST["ContactLeastFavoriteColor"];
// Connect to our DB with mysql_connect(<server>, <username>, <password>)
$sql_connection = mysql_connect("localhost", "root", "root");
mysql_select_db("MyRadContactForm", $sql_connection);
// Probably should check to make sure the connection was successful
// But I'm too lazy...
$sql = "INSERT INTO MyRadContacts (
ContactName,
ContactEmail,
ContactLeastFavoriteColor,
ContactDateCreated
)
VALUES (
'$contactName',
'$contactEmail',
'$contactLeastFavoriteColor',
NOW()
)";
mysql_query($sql, $sql_connection);
mysql_close($sql_connection);
?>
This example is lacking in a number of areas, but we aren’t going to care about SQL Injection or error-checking at this point.
Brief rundown of the above code:
Lines 4-6: We are creating three variables to store the values of our incoming form. Note that each item matches the ‘name’ attributes of our form inputs.
Line 11: This is the equivalent of the USE MyRadContactForm command that we issued earlier to our MySQL server prior to creating our table.
Line 13: This is the beginning of an SQL INSERT statement. Not surprisingly, this command inserts new records into our table. In the first set of parentheses, we specify which table columns that we want to store our data in. The second set of parentheses represent the actual values to store in the table.
Lines 20-22: PHP makes life a bit easier for us here, as it will automatically detect our variable names and replace them with the values they contain. NB: The $sql string we’ve created is surrounded with “ aka double quotes. This is crucial to get this behavior. The variable names are themselves surrounded by ‘ aka single quotes, as this is standard SQL for indicating that you are working with string values (aka VARCHAR).
Line 23: We call the MySQL built-in function NOW() to store the current date/time in ContactDateCreated at the time our insert is performed. There are other ways of handling this (such as declaring a variable in PHP), but this is easy.
Line 26: mysql_query does the actual work of sending our INSERT statement to our DB via the $sql_connection we created earlier.
Remember, this is just a primer (and not much of one at that!). Writing code like this will likely draw ire from your peers and pink slips from your employers.
Creating an HTML Contact Form Submission Viewer
So, we’ve got our form, database, table, and server-side PHP script. If all is well, we should now be adding new records to the table with each form submission.
But what good does this data do anyone if it is tucked safely away in the bowels of our MySQL server?
Let’s make a quick-and-dirty PHP page to display the input values:
<!DOCTYPE html>
<html>
<head>
<title>My Rad Contacts</title>
</head>
<body>
<?php
$sql_connection = mysql_connect("localhost", "root", "root");
mysql_select_db("MyRadContactForm", $sql_connection);
$result = mysql_query("SELECT * FROM MyRadContacts");
echo "<table>";
echo "<tr><td>Name</td><td>Email</td><td>Least Favorite Color</td><td>Created On</td></tr>";
while ($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row["ContactName"] . "</td>";
echo "<td>" . $row["ContactEmail"] . "</td>";
echo "<td>" . $row["ContactLeastFavoriteColor"] . "</td>";
echo "<td>" . $row["ContactDateCreated"] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($sql_connection);
?>
</body>
</html>
Line 12: This time, since we want to display data already in our DB, rather than insert new records, we issue a SELECT statement. The * (asterisk) tells SQL that we want every column for each row we get back. We store the data we receive in a variable named $result.
Line 14: Using PHP’s echo command, we begin the definition of our HTML table. PHP echoes its argument to the HTML page seen by the end user.
Line 17: The keyword while indicates to PHP that we want to start a loop, in which we will output the values stored in each row of our DB. When we reach the last row, the while statement is no longer true, and the loop exits.
Line 19: Again, we use echo to get our stuff out on to the HTML page. Here, we are building a table cell (<td>) that contains whatever is stored in the ContactName field for this record. Note that PHP uses a single . (dot) character to stitch strings together. This is often referred to as ‘string concatenation.’
Line 26: Finally, we use echo one last time to close our <table> tag.
UPDATE
By request, I’ve put together a zip file containing the PHP/HTML source seen above. I haven’t actually run it to verify its accuracy, so please keep that in mind.
#1 by tony jacob on January 17th, 2012
Quote
I don’t know how to arrange each of the files specified in this tutorial in other to link them together and get an output. Please I need your help there. Thanks
#2 by Priyanka on July 10th, 2012
Quote
its showing a error in “Creating PHP Server-Side Code to Store New Values”
Error is ” Undefined index: ContactName in C:\wamp\www\ContactFormHandler.php on line 4″
similarly dis is showing the same error for line 5 and 6
if possible reply as soon as possible
#3 by amal on August 28th, 2012
Quote
very useful and very nice article thank you
#4 by Jerry on August 31st, 2012
Quote
In your PHP file your variables do not match. When you establish the variable use use a lowercase C in contact but you use uppercase C when you call it.
#5 by brian on September 3rd, 2012
Quote
Jerry, you’re absolutely correct!
I’ve fixed the code and thank you for pointing that out
#6 by Ankit on October 23rd, 2012
Quote
Thanks a lot for such a wonderful article….
It worked….
For those with whom this gave some error….are
1) In that contact form ->
2) In that PHP Page
// Connect to our DB with mysql_connect(, , )
$sql_connection = mysql_connect(“localhost”, “root”, “”);
#7 by raghav on November 8th, 2012
Quote
I want e-mail sending and testimonials scripts and examples
#8 by Amriz on November 11th, 2012
Quote
Thanks and all steps are simple and well structured great learning point thanks.
#9 by Saleem Asghar on November 20th, 2012
Quote
very start up tutorial, thanks for sharing the useful information
#10 by dk on January 3rd, 2013
Quote
if you don’t mind. could you print the output?
this is great, specially to beginners.
thanks!
#11 by brian on January 3rd, 2013
Quote
Not sure what you mean… do you want me to provide a screenshot of how the HTML renders to a browser?
#12 by Amir on January 18th, 2013
Quote
I don’t know how to arrange each of the files specified in this tutorial in other to link them together and get an output. Please I need your help there. Thanks
#13 by Amir on January 18th, 2013
Quote
I Don’t know how we link these three pages with each other
#14 by Tanvirul Islam on January 30th, 2013
Quote
This is great for beginners.
#15 by brian on January 30th, 2013
Quote
Download the newly attached source – the link is at the bottom of the post.
#16 by bonbon rouge on February 7th, 2013
Quote
hmmm great
#17 by bonbon rouge on February 7th, 2013
Quote
grwat sitree for the php training
#18 by mp on March 6th, 2013
Quote
hey guys is this a valid code?
#19 by mp on March 6th, 2013
Quote
I have been looking for an actual valid script
file.php
i’d like to add those inserted data in the form to mysql.
been having troubles and i need some help and its urgent
#20 by aamena on March 26th, 2013
Quote
you are a life saver!!!!!!!!!!!
#21 by Galileo on April 3rd, 2013
Quote
Thanks a lot for the tutorial. It was really helpful to learn how to connect all th elements of a web form. I’m trying to create a local mySQL inventory and the tutorial really helps.
I just want to point out one thing for whoever is trying to implement this example. There was only one problem when using the code provided. The variable names used in the php (lines 4-6) does not match the ‘name’ attributes of the the form. Once that part of the php code was changed (see below), the form works like a charm.
Modified php Line 4-6
$contactName = $_POST["Name"];
$contactEmail = $_POST["Email"];
$contactLeastFavoriteColor = $_POST["LeastFavoriteColor"];
#22 by olap.com on April 4th, 2013
Quote
Hi this is somewhat of off topic but I was wanting to
know if blogs use WYSIWYG editors or if you have to manually code
with HTML. I’m starting a blog soon but have no coding experience so I wanted to get guidance from someone with experience. Any help would be enormously appreciated!
#23 by brian on April 4th, 2013
Quote
Hi,
I am fairly certain that most available blog software packages out there offer some sort of WYSIWYG editor. I know for a fact that WordPress comes with a WYSIWYG editor out-of-the-box.
When you need finer-grained control over the layout of your posts, I would imagine that most blogware allows direct editing of the source HTML. WordPress definitely allows direct HTML editing.
Hope this helps!