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.

ContactFormDemoSource