Using PHP and MySQL to Create a Simple Contact Form and Results Browser

By: Brian Dobberteen

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:

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:

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:

Now our new DB is the active one, and we can create our table in it:

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:

[plain light=”true”]
mysql> SHOW TABLES;
+—————————-+
| Tables in MyRadContactForm |
+—————————-+
| MyRadContacts |
+—————————-+
[/plain]

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:

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:

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.

ContactFormDemoSource



46 Responses to “Using PHP and MySQL to Create a Simple Contact Form and Results Browser”

  • tony jacob Says:

    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

  • Priyanka Says:

    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

  • amal Says:

    very useful and very nice article thank you

  • Jerry Says:

    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.

  • brian Says:

    Jerry, you’re absolutely correct!

    I’ve fixed the code and thank you for pointing that out 🙂

  • Ankit Says:

    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”, “”);

  • raghav Says:

    I want e-mail sending and testimonials scripts and examples

  • Amriz Says:

    Thanks and all steps are simple and well structured great learning point thanks.

  • Saleem Asghar Says:

    very start up tutorial, thanks for sharing the useful information

  • dk Says:

    if you don’t mind. could you print the output? 🙂 this is great, specially to beginners.

    thanks!

  • brian Says:

    Not sure what you mean… do you want me to provide a screenshot of how the HTML renders to a browser?

  • Amir Says:

    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

  • Amir Says:

    I Don’t know how we link these three pages with each other

  • Tanvirul Islam Says:

    This is great for beginners.

  • brian Says:

    Download the newly attached source – the link is at the bottom of the post.

  • bonbon rouge Says:

    grwat sitree for the php training

  • mp Says:

    hey guys is this a valid code?

  • mp Says:

    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

  • aamena Says:

    you are a life saver!!!!!!!!!!!

  • Galileo Says:

    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”];

  • olap.com Says:

    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!

  • brian Says:

    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!

  • shubham Says:

    well how to arrange ol these fileS?? form action=??? second page or d third page?? i’m confused.plz help me..

  • Adding a simple contact form to your website … easy | Innovation of the web Says:

    […] Link: http://brian.dobberteen.com/code/using-php-and-mysql-to-create-a-simple-contact-form-and-results-bro… […]

  • amit Says:

    it is rubbish

  • amit Says:

    boring and waist

  • marcus Says:

    Hey guys I need help I’m working on php, I need a form that stores values into mysql, it must save name, surname and multiple checkboxes. Please send me an email. : thokozani1marcus@gmail.com

  • churchill Says:

    Do i have to put the codes on one page or if there are two pages how do i combine them to work as one.

  • churchill Says:

    i embedded ContactFormHandler.php and ContactForm.html into my www directory of Wamp and when i type localhost/ContactForm.html i could see the form and when i click “contact me” it went to to the database.i only modified
    Modified php Line 4-6
    $contactName = $_POST[“Name”];
    $contactEmail = $_POST[“Email”];
    $contactLeastFavoriteColor = $_POST[“LeastFavoriteColor”];
    then i modified
    $sql_connection = mysql_connect(“localhost”, “root”, “root”); changing the last “root” to my own password.
    It work well with the two pages.
    The question is what is the use of the “Contactviewer.php page”?????

  • junny manglib Says:

    wow, this is a great site for the beginner…thanks for sharing your knowledge and time.

  • Mah Says:

    brian :

    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!

    Hi Brian, can you please send me the code which gives the update button to each record saved in database. Your code s excellent.. I want a update button for each record in HTML Contact Form Submission Viewer page.. please help

  • noob Says:

    the thing is, this is not for a beginners. its kind of hard. ^,^V

  • sagar dhargalkar Says:

    i dnt no how to connect to database. in above website contact form is not ready . so plz help me to solve this problem. thank you. 🙂

  • Tom Says:

    Thanks for the tips!

  • Indre Says:

    Hi Brian,

    Many thanks for this tutorial.
    I’m rather new to PHP, but getting there slowly. I was wondering if it would be possible to have a web contact form that would send an email (with the entered values) and also store the entries in a MySQL database? Or is it the case of ‘either or’? I’m trying to find info re same online, but not luck so far.

    Thanks so much!
    Indre

  • prakash Says:

    i am getting this error

    Parse error: syntax error, unexpected ‘mysql_query’ (T_STRING) in C:\xampp\htdocs\Site\Site\view_category.php on line 40 [closed]

  • prakash Says:

    i have installed xampp and copied the files inside htdocs folder after creating a test folder and i got the above error any idea.

  • sabarinath Says:

    I created database in XAmp but after that when i enter details in form field and hit submit button browser redirects to php coding of MyRad ContactForm.php

  • anum Says:

    tony jacob :

    syntax error, unexpected ‘mysql_query’ (T_STRING) in /var/www/html/RADCONTACTForm.php on line 28
    this error help me out

    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

  • anum Says:

    syntax error, unexpected ‘mysql_query’ (T_STRING) in /var/www/html/RADCONTACTForm.php on line 28
    please help me to solve error

  • chi Says:

    thanks. Great help for beginner

  • chi Says:

    thanks. Great help for beginner
    @ anum put ; the end of line 27, the error would stop.
    i.e line 26: NOW()
    line 27: )” ;
    line 28: mysql_query($sql, $sql_connection);

  • Riccardo Grosso Says:

    There is on line 26:
    echo “</table";

    🙂

  • ajr Says:

    Amir :

    I Don’t know how we link these three pages with each other

    Type your comment here

  • ajr Says:

    prakash :

    i am getting this error
    Parse error: syntax error, unexpected ‘mysql_query’ (T_STRING) in C:\xampp\htdocs\Site\Site\view_category.php on line 40 [closed]

    Type your comment here

Leave a Reply