This is a simple step by step guide to creating a form that will capture data and store it in a mysql database on your server from within a wordpress post
Note: the below example is a live, working form on this page
Step 1:
Create a simple form for a petition, contact request, or registration:
Name: | ||
---|---|---|
Address: | ||
City: | ||
State: | ||
Email: | ||
Comment: | ||
Here is the html code for it:
<table> <tr><th>Name:</th><td><input id="userName" /></td></tr> <tr><th>Address:</th><td> <input id="userAddress" /></td></tr> <tr><th>City:</th><td> <input id="userCity" /></td></tr> <tr><th>State:</th><td> <input id="userState> /></td></tr> <tr><th>Zip:</th><td> <input id="userZip" /></td></tr> <tr><th>Email:</th><td> <input id="userEmail" /></td></tr> <tr><th>Comment:</th><td> <textarea id="userComment" ></textarea></td></tr> <tr><th><td colspan=2><button type="button" onclick="saveUser();">Save</button></td></tr> </table>
Step 2:
Create a javascript function to process the form and send it to the server. The following is a javascript function added to the page using the CSS & Javascript Toolbox plugin (it uses jquery because wordpress already has that available):
//Process the form and save the data record function saveUser() { //First gather the form parameters and make sure name and email at least are populated var name = jQuery("#userName").val(); var address = jQuery("#userAddress").val(); var city = jQuery("#userCity").val(); var state = jQuery("#userState").val(); var zip = jQuery("#userZip").val(); var email = jQuery("#userEmail").val(); var comment = jQuery("#userComment").val(); if (name.length<1 || email.length<1) { alert("Please at least enter your name and email."); return false; } else { //Now send the data to a server side function to really validate it and save it. jQuery.ajax({ type: "POST", url: "/ajax/saveUser.php", data: { name:name,address:address,city:city,state:state,zip:zip,email:email,comment:comment } }).done(function( results ) { if(results.length<1){ // network error alert("There was a network error, please try again or contact support and tell them what you are trying to do."); } else { // this is a successful interaction var resultObj = jQuery.parseJSON(results); if (resultObj.errorMsg.length>0) { alert(resultObj.errorMsg); } else { //Record save successful alert("Thanks for your information, it was saved successfully!"); //Show the user what they have entered: jQuery("#userList").html(resultObj.userList); } } }); } }
Step 3:
Make sure you have a database table ready to store the information. Below is a simple table used to store the info in this example:
CREATE TABLE IF NOT EXISTS `user_info` ( `userID` int(11) NOT NULL AUTO_INCREMENT, `userName` varchar(80) DEFAULT NULL, `address` varchar(100) DEFAULT NULL, `city` varchar(80) DEFAULT NULL, `state` varchar(40) DEFAULT NULL, `zip` varchar(5) DEFAULT NULL, `email` varchar(80) DEFAULT NULL, `comment` text DEFAULT NULL, `userIP` VARCHAR( 30 ) DEFAULT NULL, `dateAdded` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`userID`), KEY `userIP` (`userIP`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
Step 4:
Create the server side code to accept the form data, really validate it, and put it in the database or send back an error. Here is the contents of a server side code which will do all that for the example data above. Since this form is “in the wild”, I’m capturing the IP address because I will only show results to people that they entered themselves:
/* * File: saveUser.php * Description: This file takes the passed in user information and validates it before * saving it to the database and returning content to show on the page. * Inputs (in POST): * userName, address, city, state, zip, email, comment * Outputs: * either an error or nothing */ include("db.php"); // define your database credentials in another file #connect to the database $db = mysqli_connect($servername, $username, $password, $dbname); mysqli_select_db($db,$dbname) or die('Could not select database'); #Get the passed in parameters into local variables, escaped for database input $userName = empty($_POST['userName'])?'':addslashes($_POST['userName']); $address = empty($_POST['address'])?'':addslashes($_POST['address']); $city = empty($_POST['city'])?'':addslashes($_POST['city']); $state = empty($_POST['state'])?'':addslashes($_POST['state']); //only accept 5 numbers for zip $zip = empty($_POST['zip'])?'':substr(preg_replace('/\D/','',$_POST['zip']),0,5); $email = empty($_POST['email'])?'':addslashes($_POST['email']); $comment = empty($_POST['comment'])?'':addslashes($_POST['comment']); $userIP = $_SERVER['REMOTE_ADDR']; #This is an array used for gathering all the outputs of this file $jsonObj = array(); $jsonObj['errorMsg'] = ""; $debug=false; #Validate inputs if (empty($userName) or empty($email)) { $jsonObj['errorMsg'] = "Please at least enter your name and email."; } else if (strpos($email,'@')===false) { //there are many more validations that can be made for emails but this is a start $jsonObj['errorMsg'] = "Please enter a valid email."; } #Enter the data record if (empty($jsonObj['errorMsg'])) { $sql = "insert into user_info (userName,address,city,state,zip,email,comment,userIP) values ('".$userName."','".$address."','".$city."','".$state."','".$zip."','".$email."', '".$comment."','".$userIP."')"; if ($debug) echo "about to run $sql "; mysqli_query($db, $sql); $err = mysqli_error($db); if (!empty($err)) $jsonObj['errorMsg'] = $err; } #Now get the list of data entered by this IP, without any script tags to prevent XSS: $jsonObj['userList']=''; if (empty($jsonObj['errorMsg'])) { $sql = "select userName,city,state from user_info where userIP='".$userIP."'"; $rs = mysqli_query($db, $sql); $err = mysqli_error($db); if (!empty($err)) $jsonObj['errorMsg'] = $err; while($row = mysqli_fetch_assoc($rs)) { $jsonObj['userList'].= "<tr><td>".strip_tags($row['userName'])."</td><td>".strip_tags($row['city']). "</td><td>".strip_tags($row['state'])."</td></tr>"; } } #Now send back the data in json format echo json_encode($jsonObj);
Step 5:
Do something with the results! You could export them, feed them into another system using an API, send them in an email to someone, or just display them like so:
Name | City | State |
---|---|---|
You have not entered any user records yet, try it out! |