Sample form to submit to a database

Greg K's picture

He has: 2,145 posts

Joined: Nov 2003

I had to create this sample for someone else elsewhere, so figured, might as well share it here. It is a basic form for collecting info and saving it to a DB. Optionally, after the write to DB, you can have it send e-mail too (or replace write to BD section with just mail)

Sigh... All the code WAS properly indented, however... the forum ripped half of it..


Here is a sample shell I use for most basic forms. Some of this code I do a little different, but have it broken out here for easier reading/learning of how it works.

Some notes on this:

This has two items to help prevent bot spam submissions:
1. Uses a honeypot which is needed to be left blank for submit to work
2. Sets a timestamp on the form, and then when submitted makes sure it was submitted in a timely fashion. (time is set at top of file)

Please note, I do not normally directly use the actual time() value. Anyone wanting to write a bot to spam ya, will most likely figure that out. I convert this number over to a 32 char hash (not a true hash like md5) in a way it will not easily be figures out

Also, there is a that will contain any errors from the server side validation. This actual tag is not part of the IF statement, so that the div always exists so if you have JS validation it can use this div to display client side validation.

All of the HTML code is stripped down for simplicity here, but it does work.




$aryErr = array(); // Will hold error messages

    // Note, I use a honeypot to help prevent bot spam see end of <form> code
if (count($_POST)>0 && isset($_POST['hidPostHash']) && isset($_POST['URL']) && $_POST['URL']=='') { // Form submitted

        // Clear any fiels with just whitespace back to being blank for validation
foreach($_POST as $key=>$val) { if (is_string($val)) ($_POST[$key]=trim($val)); }

// BEGIN: Validation

            // Required fields

if (!isset($_POST['txtFirstName']) || strlen($_POST['txtFirstName'])<3) {
$aryErr['FirstName'] = 'First Name must be at least 3 characters';
            if (!isset(
$_POST['txtLastName']) || strlen($_POST['txtLastName'])<3) {
$aryErr['LastName'] = 'First Name must be at least 3 characters';
            if (!isset(
$_POST['drpState']) || (int)$_POST['drpState']==0) {
$aryErr['State'] = 'You must select a state';

// Optional Fields that require certain formats (dates/phone numbers)

if (isset($_POST['txtDOB']) && $_POST['txtDOB']!='' && !preg_match('%^\d?\d[-/]\d?\d[-/]\d\d(\d\d)?$%',$_POST['txtDOB'])) {
$aryErr['DOB'] = 'Date of birth must be left blank or be in MM-DD-YYYY format';
            else {
// Note, other checking should be done to make sure a valid date at least 13 years ago

// Make sure they submitted it in a timely fashion, (ie not a programmed bot) if no other errors

if (count($aryErr) == 0) {
$tsOriginalForm = (int)$_POST['hidPostHash']; // SEE MOTES IN MY POST

if ($tsOriginalForm + (MINUTES_TO_SUBMIT*60) < time()) {
$aryErr['FORM'] = "You took too long submitting this form, try again";

// END: Validation

if (count($aryErr)==0) { // All submited data is good

            // This block is based upon that all fields that should go to DB are prefixed with either:
            //    txt = text data
            //    drp = numeric data from a dropdown/option list which will be a foreign key to other table
            //    If you have others, just keep adding elseif's to handle those
            //  You have a field called tsCreated which is a DATETIME format for when record was added
            //  You have a field called ipCreated which is varchar(15) for the IP that submitted the info

$SQL1 = 'INSERT INTO `tblName` (';
$SQL2 = ') VALUES (';
            foreach (
$_POST as $key=>$val) {
$strPrefix = substr($key,0,3); // used more than once, store it
if (strlen($key)>4) {
                    if (
$strPrefix=='txt') {
$SQL1 .= '`'.substr($key,3).'`,';
$SQL2 .= "'".addslashes($val)."',";
                    elseif (
$strPrefix=='drp') {
$SQL1 .= '`'.substr($key,3).'`,';
$SQL2 .= (int)$val.","// (int) forces to be an interger value, so no need for quotes
// Note for the following both $SQL1 and $SQL2 are already ending in a comma for next field/value
$SQL = $SQL1 . '`tsCreated`,`ipCreated`' . $SQL2 . "NOW(),'".$_SERVER['REMOTE_ADDR']."')";

// This is basic for purpose of sample code...
mysql_query($SQL) or die("Error Saving Data...");

// I do a redirect to the thank you page so that can easier track that it was properly submitted in statistics


    else {
// The form was not submitted, for ALL drpWhatever fields, define their defaults.
        // The function below handles txt fields, so no need to prefine them unless you want them filled

$_POST['drpState'] = 35; // For me, auto selects Ohio

// Note, need to load up an array of states here... either from Database of an include...
$aryStates = array(35=>'Ohio',36=>'Oklahoma',37=>'Oregon',38=>'Pennsylvania');

$strPostHosh = time(); // SEE NOTES IN MY POST

function echo_value($key) {
        if (isset(
$_POST['txt'.$key])) {


<title>My Site - Give me some data!</title>
<h1>Submit me some data!</h1>
<p>Please use the following form to sign up/suggest something/contact us... whatever...</p>
<div id='form-error'>
<?php if (count($aryErr)>0): ?>
<p>The following errors were found:</p>
<?php echo '<ul><li>',implode('</li><li>',$aryErr),'</li></ul>'; ?>
<?php endif; ?>
<form method="post" action="#">
<p>All fields marked with a * are required.</p>

<label for="txtFirstName">First Name *</label>
<input name="txtFirstName" id="txtFirstName" value="<?php echo_value('FirstName'); ?>" />
<br />
<label for="txtLastName">First Name *</label>
<input name="txtLastName" id="txtLastName" value="<?php echo_value('LastName'); ?>" />
<br />
<label for="txtDOB">Date of Birth <em>(MM-DD-YYYY)</em></label>
<input name="txtDOB" id="txtDOB" value="<?php echo_value('DOB'); ?>" />
<br />
<label for="drpState">State *</label>
<select name="drpState" id="drpState">
<option value="0" style="font-style: italic">--Select One--</option>
foreach($aryStates as $key=>$val) {
                    if (
$key == $_POST['drpState']) {
'<option value="',$key,'" selected="selected">',htmlspecialchars($val),"</option>\n";
                    else {
'<option value="',$key,'">',htmlspecialchars($val),"</option>\n";

<br />
<label for="txtComments">Comments</label>
<textarea cols="50" rows="4" name="txtComments" id="txtComments"><?php echo_value('Comments'); ?></textarea>

<div style="margin-left: -8872px; height: 10px;">This field must be left blank <input type="text" name="URL" value="" /></div>

<input type="hidden" name="hidPostHash" value="<?php echo $strPostHosh; ?>" />
<input type="submit" name="submit" value="Save Data" />