PHP mySQL code posting extra rows to database? - php

SECOND EDIT
It seems that upon loading the page, not when submitting, that the two entries (blank rows) are added to my database. I'm really struggling to find my problem here but I have a feeling it's a fairly stupid error.
I'm having an issue with my php/mysql code posting extra blank rows along with what it's supposed to post. The code for the validation of the data from my form an for the transmission of the info to the database is below. Every time I enter data in my form and submit it it works fine, however it adds extra rows to the tblLocation, the tblWhere works fine. Can anyone lead me in the right direction here? Let me know if you need more of my code.
CODE IS AS FOLLOWS
if (isset($_POST['butSubmit'])) {
// set variables to data from form
$user= mysql_real_escape_string($_POST["txtUser"]);
$fName= mysql_real_escape_string($_POST["txtFname"]);
$lName= mysql_real_escape_string($_POST["txtLname"]);
$email= mysql_real_escape_string($_POST["txtEmail"]);
$date= date(DATE_RFC822);
$street= mysql_real_escape_string($_POST["txtStreet"]);
$city= mysql_real_escape_string($_POST["txtCity"]);
$state= mysql_real_escape_string($_POST["lstStates"]);
$zip= mysql_real_escape_string($_POST["txtZip"]);
//handle html characters
$user = htmlentities($user, ENT_QUOTES);
$fName = htmlentities($fName, ENT_QUOTES);
$lName = htmlentities($lName, ENT_QUOTES);
$email = htmlentities($email, ENT_QUOTES);
$date = htmlentities($date, ENT_QUOTES);
$street = htmlentities($street, ENT_QUOTES);
$city = htmlentities($city, ENT_QUOTES);
$state = htmlentities($state, ENT_QUOTES);
$zip = htmlentities($zip, ENT_QUOTES);
$errorMsg=array();
// initiate testing procedures for form contents
if($user==""){
$errorMsg[]="Please enter your Username";
} else {
$valid = verifyAlphaNum ($user); /* test for non-valid data */
if (!$valid){
$error_msg[]="Username must contain only letters (A-Z), numbers (0-9), spaces, dashes(-), and apostrophes (').";
}
}
if($fName==""){
$errorMsg[]="Please enter your First Name";
} else {
$valid = verifyAlphaNum ($fName); /* test for non-valid data */
if (!$valid){
$error_msg[]="First Name must contain only letters (A-Z), numbers (0-9), spaces, dashes(-), and apostrophes (').";
}
}
if($lName==""){
$errorMsg[]="Please enter your Last Name";
} else {
$valid = verifyAlphaNum ($lName); /* test for non-valid data */
if (!$valid){
$error_msg[]="Last Name must contain only letters (A-Z), numbers (0-9), spaces, dashes(-), and apostrophes (').";
}
}
if($email==""){
$errorMsg[]="Please enter your Email Address";
} elseif (!verifyEmail($email)){
$errorMsg[]="Correct eMail format is ( example#anysite.com )";
}
if($street==""){
$errorMsg[]="Please enter your Street Address";
} else {
$valid = verifyAlphaNum ($street); /* test for non-valid data */
if (!$valid){
$error_msg[]="Street Address must contain only letters (A-Z), numbers (0-9), spaces, dashes(-), and apostrophes (').";
}
}
if($city==""){
$errorMsg[]="Please enter a City";
} else {
$valid = verifyAlphaNum ($city); /* test for non-valid data */
if (!$valid){
$error_msg[]="City must contain only letters (A-Z), numbers (0-9), spaces, dashes(-), and apostrophes (').";
}
}
if($state==""){
$errorMsg[]="Please choose a State";
} else {
$valid = verifyAlphaNum ($state); /* test for non-valid data */
}
}
if($errorMsg){
echo "<ul>\n";
foreach($errorMsg as $err){
echo "<li style='color: #ff6666'>" . $err . "</li>\n";
}
echo "</ul>\n";
} else {
mysql_query("INSERT INTO tblWhere (pk_Username, fldFirstName, fldLastName, fldAdminLevel, fldTotalPosts, fldDateJoined, fldEmail) VALUES ('$user', '$fName', '$lName', '4', '0', '$date', '$email')");
if (mysql_errno()) {
echo $sql . "<br/>\n" . mysql_error();
}
mysql_query("INSERT INTO tblLocation (fk_Username, fldStreet, fldCity, fldState, fldZip) VALUES ('$user', '$street', '$city', '$state', '$zip')");
if (mysql_errno()) {
echo $sql . "<br/>\n" . mysql_error();
}
}
mysql_close();
print $user;
EDIT
Here is the full code, maybe this will help?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>CS148 "Where Are You From?" Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="author" content="Stephen B. Wakita" />
<meta name='description' content='Form to gather information for CS148 PHP Form Assignment. The javascript functions for validation are from Easy! Designs, LLC easydesigns.net and few by Robert Erickson.'/>
<link rel="stylesheet"
href="mystyle.css"
type="text/css"
media="screen" />
<script src="validation.js" type="text/javascript"></script>
<script type="text/javascript">
<!--
window.onload = Initialize;
function Initialize(){
if (!document.getElementById || !document.createElement || !document.createTextNode)
return;
var objForm = document.getElementById('frmRegister');
objForm.onsubmit= function(){return fblnVerified(this);};
}
function reSetForm(){
document.getElementById('txtFname').style.background='#fff';
document.getElementById('txtLname').style.background='#fff';
document.getElementById('txtEmail').style.background='#fff';
document.getElementById('lstStates').style.background='#fff';
document.getElementById('errors').innerHTML="";
}
function fblnVerified(theForm){
reSetForm();
returnStatus = true;
errorMsg = "";
numErrors = 0;
if (isEmpty(theForm.txtFname.value)) {
document.getElementById('txtFname').style.background='#FF6';
errorMsg += "<li>Please enter your first name.</li>";
numErrors += 1;
returnStatus = false;
}
if (isEmpty(theForm.txtLname.value)) {
document.getElementById('txtLname').style.background='#FF6';
errorMsg += "<li>Please Enter your last name.</li>";
numErrors += 1;
returnStatus = false;
} else if (!isWithinRange(theForm.txtLname.value.length, 2, 45)){
document.getElementById('txtLname').style.background='#FF6';
errorMsg += "<li>Last name must contain at least two characters.</li>";
numErrors += 1;
returnStatus = false;
}
if (isEmpty(theForm.txtEmail.value)) {
document.getElementById('txtEmail').style.background='#FF6';
errorMsg += "<li>Please enter your email address.</li>";
numErrors += 1;
returnStatus = false;
}else if (!isEmailAddress(theForm.txtEmail.value)){
document.getElementById('txtEmail').style.background='#FF6';
errorMsg += "<li>You have entered your email in an invalid format, please use this format: example#example.xxx </li>";
numErrors += 1;
returnStatus = false;
}
if(returnStatus == false){
msg1 = "Your form is incomplete or incorrect. There are " + numErrors + " errors. ";
msg1 += "Please look for the highlighted items.";
msg = "<p>" + msg1 + "</p><ol class='missing' id='errorMessages'></ol>";
document.getElementById('errors').innerHTML = msg;
document.getElementById('errorMessages').innerHTML= errorMsg;
alert(msg1);
window.scrollTo(0,0);
}
return returnStatus;
}
-->
</script>
</head>
<body class="bodycolor">
<div id="content">
<div id="errors">
</div>
<form action="form.php"
method="post"
id="frmWhere">
<fieldset class="wrapper">
<legend>Where are you from?</legend>
<p>Please answer the following survey. Required fields are marked in <span class="required">red</span>.</p>
<fieldset class="intro">
<legend>Please complete the following survey.</legend>
<fieldset class="main">
<legend>Contact Information</legend>
<fieldset class="info">
<label for="txtUser" class="required">Username</label>
<input type="text" id="txtUser" name="txtUser" value="" tabindex="260"
size="30" maxlength="26" onfocus="this.select()" />
<label for="txtFname" class="required">First Name</label>
<input type="text" id="txtFname" name="txtFname" value="" tabindex="261"
size="55" maxlength="45" onfocus="this.select()" />
<label for="txtLname" class="required">Last Name</label>
<input type="text" id="txtLname" name="txtLname" value="" tabindex="262"
size="55" maxlength="45" onfocus="this.select()" />
<label for="txtEmail" class="required">Email</label>
<input type="text" id="txtEmail" name="txtEmail" value="" tabindex="263"
size="55" maxlength="45" onfocus="this.select()" />
<label for="txtstreet" class="required">Street Address</label>
<input type="text" id="txtStreet" name="txtStreet" value="" tabindex="264"
size="55" maxlength="45" onfocus="this.select()" />
<label for="txtCity" class="required">City</label>
<input type="text" id="txtCity" name="txtCity" value="" tabindex="265"
size="55" maxlength="45" onfocus="this.select()" />
<select id="lstStates" name="lstStates" tabindex="266" size="1">
<option value="ZZ">None</option>
<option value="">-- UNITED STATES --</option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
<option value="AR">Arkansas</option>
<option value="CA">California</option>
<option value="CO">Colorado</option>
<option value="CT">Connecticut</option>
<option value="DE">Delaware</option>
<option value="FL">Florida</option>
<option value="GA">Georgia</option>
<option value="HI">Hawaii</option>
<option value="ID">Idaho</option>
<option value="IL">Illinois</option>
<option value="IN">Indiana</option>
<option value="IA">Iowa</option>
<option value="KS">Kansas</option>
<option value="KY">Kentucky</option>
<option value="LA">Louisiana</option>
<option value="ME">Maine</option>
<option value="MD">Maryland</option>
<option value="MA">Massachusetts</option>
<option value="MI">Michigan</option>
<option value="MN">Minnesota</option>
<option value="MS">Mississippi</option>
<option value="MO">Missouri</option>
<option value="MT">Montana</option>
<option value="NE">Nebraska</option>
<option value="NV">Nevada</option>
<option value="NH">New Hampshire</option>
<option value="NJ">New Jersey</option>
<option value="NM">New Mexico</option>
<option value="NY">New York</option>
<option value="NC">North Carolina</option>
<option value="ND">North Dakota</option>
<option value="OH">Ohio</option>
<option value="OK">Oklahoma</option>
<option value="OR">Oregon</option>
<option value="PA">Pennsylvania</option>
<option value="RI">Rhode Island</option>
<option value="SC">South Carolina</option>
<option value="SD">South Dakota</option>
<option value="TN">Tennessee</option>
<option value="TX">Texas</option>
<option value="UT">Utah</option>
<option value="VT">Vermont</option>
<option value="VA">Virginia</option>
<option value="WA">Washington</option>
<option value="DC">Washington, DC</option>
<option value="WV">West Virginia</option>
<option value="WI">Wisconsin</option>
<option value="WY">Wyoming</option>
<option value="">-- CANADA --</option>
<option value="AB">Alberta</option>
<option value="BC">British Columbia</option>
<option value="MB">Manitoba</option>
<option value="NB">New Brunswick</option>
<option value="NF">Newfoundland and Labrador</option>
<option value="NT">Northwest Territories</option>
<option value="NS">Nova Scotia</option>
<option value="NU">Nunavut</option>
<option value="ON">Ontario</option>
<option value="PE">Prince Edward Island</option>
<option value="PQ">Quebec</option>
<option value="SK">Saskatchewan</option>
<option value="YT">Yukon Territory</option>
<option value="">-- OTHER --</option>
<option value="OT">Other</option>
</select>
<label for="txtZip" class="required">ZIP Code</label>
<input type="text" id="txtZip" name="txtZip" value="" tabindex="267"
size="6" maxlength="6" onfocus="this.select()" />
<fieldset class="buttons">
<legend></legend>
<input type="submit" id="butSubmit" name="butSubmit" value="Submit"
tabindex="991" class="button"/>
<input type="reset" id="butReset" name="butReset" value="Reset Form"
tabindex="993" class="button" onclick="reSetForm()" />
</fieldset>
</fieldset>
</fieldset>
</fieldset>
</form>
</?php
include ("validation_functions.php");
date_default_timezone_set('UTC');
$dbh=mysql_connect('webdb.uvm.edu','swakita','password');
if (!$dbh)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('SWAKITA', $dbh);
if (isset($_POST['butSubmit'])) {
//handle html characters
$user = htmlentities($user, ENT_QUOTES);
$fName = htmlentities($fName, ENT_QUOTES);
$lName = htmlentities($lName, ENT_QUOTES);
$email = htmlentities($email, ENT_QUOTES);
$date = htmlentities($date, ENT_QUOTES);
$street = htmlentities($street, ENT_QUOTES);
$city = htmlentities($city, ENT_QUOTES);
$state = htmlentities($state, ENT_QUOTES);
$zip = htmlentities($zip, ENT_QUOTES);
$errorMsg=array();
// set variables to data from form
$user= mysql_real_escape_string($_POST["txtUser"]);
$fName= mysql_real_escape_string($_POST["txtFname"]);
$lName= mysql_real_escape_string($_POST["txtLname"]);
$email= mysql_real_escape_string($_POST["txtEmail"]);
$date= date(DATE_RFC822);
$street= mysql_real_escape_string($_POST["txtStreet"]);
$city= mysql_real_escape_string($_POST["txtCity"]);
$state= mysql_real_escape_string($_POST["lstStates"]);
$zip= mysql_real_escape_string($_POST["txtZip"]);
// initiate testing procedures for form contents
if($user==""){
$errorMsg[]="Please enter your Username";
} else {
$valid = verifyAlphaNum ($user); /* test for non-valid data */
if (!$valid){
$error_msg[]="Username must contain only letters (A-Z), numbers (0-9), spaces, dashes(-), and apostrophes (').";
}
}
if($fName==""){
$errorMsg[]="Please enter your First Name";
} else {
$valid = verifyAlphaNum ($fName); /* test for non-valid data */
if (!$valid){
$error_msg[]="First Name must contain only letters (A-Z), numbers (0-9), spaces, dashes(-), and apostrophes (').";
}
}
if($lName==""){
$errorMsg[]="Please enter your Last Name";
} else {
$valid = verifyAlphaNum ($lName); /* test for non-valid data */
if (!$valid){
$error_msg[]="Last Name must contain only letters (A-Z), numbers (0-9), spaces, dashes(-), and apostrophes (').";
}
}
if($email==""){
$errorMsg[]="Please enter your Email Address";
} elseif (!verifyEmail($email)){
$errorMsg[]="Correct eMail format is ( example#anysite.com )";
}
if($street==""){
$errorMsg[]="Please enter your Street Address";
} else {
$valid = verifyAlphaNum ($street); /* test for non-valid data */
if (!$valid){
$error_msg[]="Street Address must contain only letters (A-Z), numbers (0-9), spaces, dashes(-), and apostrophes (').";
}
}
if($city==""){
$errorMsg[]="Please enter a City";
} else {
$valid = verifyAlphaNum ($city); /* test for non-valid data */
if (!$valid){
$error_msg[]="City must contain only letters (A-Z), numbers (0-9), spaces, dashes(-), and apostrophes (').";
}
}
if($state==""){
$errorMsg[]="Please choose a State";
} else {
$valid = verifyAlphaNum ($state); /* test for non-valid data */
}
}
if($errorMsg){
echo "<ul>\n";
foreach($errorMsg as $err){
echo "<li style='color: #ff6666'>" . $err . "</li>\n";
}
echo "</ul>\n";
} else {
mysql_query("INSERT INTO tblWhere (pk_Username, fldFirstName, fldLastName, fldAdminLevel, fldTotalPosts, fldDateJoined, fldEmail) VALUES ('$user', '$fName', '$lName', '4', '0', '$date', '$email')");
if (mysql_errno()) {
echo $sql . "<br/>\n" . mysql_error();
}
mysql_query("INSERT INTO tblLocation (fk_Username, fldStreet, fldCity, fldState, fldZip) VALUES ('$user', '$street', '$city', '$state', '$zip')");
if (mysql_errno()) {
echo $sql . "<br/>\n" . mysql_error();
}
}
mysql_close();
print $user;
?>
</body>
</html>

Your code runs the mysql query outside of the POST check, the mysql query runs no matter what because $errorMsg is not being returned.
Move your mysql logic inside the if (isset($_POST['butSubmit'])) { part of your code.
<?php
include ("validation_functions.php");
date_default_timezone_set('UTC');
$dbh=mysql_connect('webdb.uvm.edu','swakita','password');
if (!$dbh)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('SWAKITA', $dbh);
if (isset($_POST['butSubmit'])) {
//handle html characters
$user = htmlentities($user, ENT_QUOTES);
$fName = htmlentities($fName, ENT_QUOTES);
$lName = htmlentities($lName, ENT_QUOTES);
$email = htmlentities($email, ENT_QUOTES);
$date = htmlentities($date, ENT_QUOTES);
$street = htmlentities($street, ENT_QUOTES);
$city = htmlentities($city, ENT_QUOTES);
$state = htmlentities($state, ENT_QUOTES);
$zip = htmlentities($zip, ENT_QUOTES);
$errorMsg=array();
// set variables to data from form
$user= mysql_real_escape_string($_POST["txtUser"]);
$fName= mysql_real_escape_string($_POST["txtFname"]);
$lName= mysql_real_escape_string($_POST["txtLname"]);
$email= mysql_real_escape_string($_POST["txtEmail"]);
$date= date(DATE_RFC822);
$street= mysql_real_escape_string($_POST["txtStreet"]);
$city= mysql_real_escape_string($_POST["txtCity"]);
$state= mysql_real_escape_string($_POST["lstStates"]);
$zip= mysql_real_escape_string($_POST["txtZip"]);
// initiate testing procedures for form contents
if($user==""){
$errorMsg[]="Please enter your Username";
} else {
$valid = verifyAlphaNum ($user); /* test for non-valid data */
if (!$valid){
$error_msg[]="Username must contain only letters (A-Z), numbers (0-9), spaces, dashes(-), and apostrophes (').";
}
}
if($fName==""){
$errorMsg[]="Please enter your First Name";
} else {
$valid = verifyAlphaNum ($fName); /* test for non-valid data */
if (!$valid){
$error_msg[]="First Name must contain only letters (A-Z), numbers (0-9), spaces, dashes(-), and apostrophes (').";
}
}
if($lName==""){
$errorMsg[]="Please enter your Last Name";
} else {
$valid = verifyAlphaNum ($lName); /* test for non-valid data */
if (!$valid){
$error_msg[]="Last Name must contain only letters (A-Z), numbers (0-9), spaces, dashes(-), and apostrophes (').";
}
}
if($email==""){
$errorMsg[]="Please enter your Email Address";
} elseif (!verifyEmail($email)){
$errorMsg[]="Correct eMail format is ( example#anysite.com )";
}
if($street==""){
$errorMsg[]="Please enter your Street Address";
} else {
$valid = verifyAlphaNum ($street); /* test for non-valid data */
if (!$valid){
$error_msg[]="Street Address must contain only letters (A-Z), numbers (0-9), spaces, dashes(-), and apostrophes (').";
}
}
if($city==""){
$errorMsg[]="Please enter a City";
} else {
$valid = verifyAlphaNum ($city); /* test for non-valid data */
if (!$valid){
$error_msg[]="City must contain only letters (A-Z), numbers (0-9), spaces, dashes(-), and apostrophes (').";
}
}
if($state==""){
$errorMsg[]="Please choose a State";
} else {
$valid = verifyAlphaNum ($state); /* test for non-valid data */
}
if($errorMsg){
echo "<ul>\n";
foreach($errorMsg as $err){
echo "<li style='color: #ff6666'>" . $err . "</li>\n";
}
echo "</ul>\n";
} else {
mysql_query("INSERT INTO tblWhere (pk_Username, fldFirstName, fldLastName, fldAdminLevel, fldTotalPosts, fldDateJoined, fldEmail) VALUES ('$user', '$fName', '$lName', '4', '0', '$date', '$email')");
if (mysql_errno()) {
echo $sql . "<br/>\n" . mysql_error();
}
mysql_query("INSERT INTO tblLocation (fk_Username, fldStreet, fldCity, fldState, fldZip) VALUES ('$user', '$street', '$city', '$state', '$zip')");
if (mysql_errno()) {
echo $sql . "<br/>\n" . mysql_error();
}
}
}
mysql_close();
print $user;
?>
</body>
</html>

PHP Mysql won't insert blank rows magically so you may check what you are really trying to INSERT, or using some debug echo $query statements just before your query, or even better using *print_r(debug_backtrace())*

Related

PHP Form Data Validation + Redirect

I have a form I need to create in PHP that needs to validate the data that is entered and send it through if everything is in order. It took me awhile to get to it but it redirects if all forms are filled out properly. However, the reception page does not get the data from the form page. Can I apply two actions to the form? How else do I send the data both to itself ($_SERVER["PHP_SELF"]) and another page? I am getting the Undefined index error on all my variable definitions in the reception page.
Here is the code for the form page:
<!DOCTYPE html>
<!-- Jonathan DeMars
4/20/2017
http://chelan.highline.edu/~jon_demars3/116/magazine.html
-->
<html lang="en">
<head>
<meta charset="utf-8">
<title>GQ - Subscription</title>
<meta name="description" content="Register to GQ">
<meta name="author" content="CSCI 116 Student: Jonathan DeMars">
<link rel="stylesheet"
type="text/css"
href="styles.css">
</head>
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
?>
<body>
<h1>Register to GQ</h1>
<p>GQ or "Gentleman's Quarterly" is an international monthly men's magazine based in New York City. The publication focuses on fashion, style,
and culture for men; though articles on food, movies, fitness, sex, music, travel, sports, technology,
and books are also featured.</p>
<hr>
<br>
<p><strong>Please complete the following form:</strong></p>
<?php
$firstnameErr = $lastnameErr = $addressErr = $cityErr = $zipcodeErr = $monthsErr = "";
$first_name = $last_name = $address = $city = $zipcode = $months = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$first_name = test_input($_POST["first_name"]);
$last_name = test_input($_POST["last_name"]);
$address = test_input($_POST["address"]);
$city = test_input($_POST["city"]);
$zipcode = test_input($_POST["zipcode"]);
$months = test_input($_POST["months"]);
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["first_name"])) {
$firstnameErr = "First name is required";
} else {
$first_name = test_input($_POST["first_name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$first_name)) {
$firstnameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["last_name"])) {
$lastnameErr = "Last name is required";
} else {
$last_name = test_input($_POST["last_name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$last_name)) {
$lastnameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["address"])) {
$addressErr = "Address is required";
} else {
$address = test_input($_POST["address"]);
}
if (empty($_POST["city"])) {
$cityErr = "City is required";
} else {
$city = test_input($_POST["city"]);
if (!preg_match("/^[a-zA-Z ]*$/",$city)) {
$cityErr = "Only letters and white space allowed";
}
}
if (empty($_POST["zipcode"])) {
$zipcodeErr = "Zipcode is required";
} else {
$zipcode = test_input($_POST["zipcode"]);
if (!preg_match("/^([0-9]{5})(-[0-9]{4})?$/i",$zipcode)) {
$zipcodeErr = "Please enter a valid zipcode.";
}
}
if (empty($_POST["months"])) {
$monthsErr = "You must subscribe for 1 or more months.";
} else {
$months = test_input($_POST["months"]);
if (!preg_match("/^[1-9][0-9]*$/",$months)) {
$monthsErr = "Must enter a valid number.";
}
}
}
if($firstnameErr == "" && $lastnameErr == "" && $addressErr == "" && $cityErr == "" && $zipcodeErr == "" && $monthsErr == ""){
header('Location: magazinevalidation_post.php');
exit();
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<p>First Name: <input type="text" name="first_name" size="15" value="<?php echo $first_name;?>" <span class="error">* <?php echo $firstnameErr;?></span>
Last Name: <input type="text" name="last_name" size="15" value="<?php echo $last_name;?>" <span class="error">* <?php echo $lastnameErr;?></span></p>
<br>
<p>Address: <input type="text" name="address" size="20" value="<?php echo $address;?>" <span class="error">* <?php echo $addressErr;?></span></p>
<p>City: <input type="text" name="city" size="15" value="<?php echo $city;?>" <span class="error">* <?php echo $cityErr;?></span> </p>
<p>State: <select name="state">
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
<option value="AR">Arkansas</option>
<option value="CA">California</option>
<option value="CO">Colorado</option>
<option value="CT">Connecticut</option>
<option value="DE">Delaware</option>
<option value="DC">District of Columbia</option>
<option value="FL">Florida</option>
<option value="GA">Georgia</option>
<option value="HI">Hawaii</option>
<option value="ID">Idaho</option>
<option value="IL">Illinois</option>
<option value="IN">Indiana</option>
<option value="IA">Iowa</option>
<option value="KS">Kansas</option>
<option value="KY">Kentucky</option>
<option value="LA">Louisiana</option>
<option value="ME">Maine</option>
<option value="MD">Maryland</option>
<option value="MA">Massachusetts</option>
<option value="MI">Michigan</option>
<option value="MN">Minnesota</option>
<option value="MS">Mississippi</option>
<option value="MO">Missouri</option>
<option value="MT">Montana</option>
<option value="NE">Nebraska</option>
<option value="NV">Nevada</option>
<option value="NH">New Hampshire</option>
<option value="NJ">New Jersey</option>
<option value="NM">New Mexico</option>
<option value="NY">New York</option>
<option value="NC">North Carolina</option>
<option value="ND">North Dakota</option>
<option value="OH">Ohio</option>
<option value="OK">Oklahoma</option>
<option value="OR">Oregon</option>
<option value="PA">Pennsylvania</option>
<option value="RI">Rhode Island</option>
<option value="SC">South Carolina</option>
<option value="SD">South Dakota</option>
<option value="TN">Tennessee</option>
<option value="TX">Texas</option>
<option value="UT">Utah</option>
<option value="VT">Vermont</option>
<option value="VA">Virginia</option>
<option value="WA">Washington</option>
<option value="WV">West Virginia</option>
<option value="WI">Wisconsin</option>
<option value="WY">Wyoming</option>
</select>
<p>Zip Code: <input type="text" name="zipcode" size="4" value="<?php echo $zipcode;?>" <span class="error">* <?php echo $zipcodeErr;?></p>
<br>
<br>
<p>How many months would you like to subscribe? <input type="text" name="months" size="1" value="<?php echo $months;?>" <span class="error">* <?php echo $monthsErr;?></span></p>
<br>
<br>
<input type="submit" name="submit" value="Continue" />
</form>
<p>Return to index page</p>
</body>
</html>
And here is the code for the reception page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>GQ - Thank you!</title>
<meta name="description" content="Thank you for Registering to GQ">
<meta name="author" content="CSCI 116 Student: Jonathan DeMars">
<link rel="stylesheet"
type="text/css"
href="styles.css">
</head>
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
?>
<body>
<?php
echo "<h1>Order Summary</h1><hr>";
define("TAX", "0.10");
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$address = $_POST['address'];
$city = $_POST['city'];
$state = $_POST['state'];
$zipcode = $_POST['zipcode'];
$months = $_POST['months'];
$name = $first_name . ' ' . $last_name;
$monthlyrate = 9.99;
$subtotal = $months * $monthlyrate;
$taxtotal = $subtotal * TAX;
$grandtotal = $subtotal + $taxtotal;
print "<p><strong>$name</strong></p>";
print "<strong>$address</strong><br>";
print "<strong>$city, $state $zipcode</strong><br>";
print "<p>Your Subscription: <strong>$months months</strong></p>";
print "Monthly Payments: <strong>$$subtotal</strong><br>";
print "Tax:";
echo "<strong> $";
echo round($taxtotal, 2, PHP_ROUND_HALF_UP);
echo "</strong>";
print "<br>Total:";
echo "<strong> $";
echo round($grandtotal, 2, PHP_ROUND_HALF_UP);
echo "</strong>";
print "<div><p>Thank you, $name, for your subscription. You will recieve your first copy of GQ within the week!
</p></div>";
?>
<p>Return to index page</p>
</body>
</html>
You can use the session for pass the data to another form. Before redirect set the values in session after you can access these data in form2 with using session variables.
$_SESSION - probably best way
<?php
session_start();
$_SESSION['first_name'] = $first_name;
$_SESSION['last_name'] = $last_name;
$_SESSION['address'] = $address;
$_SESSION['city'] = $city;
$_SESSION['address'] = $address;
$_SESSION['zipcode'] = $zipcode;
$_SESSION['months'] = $months;
header('Location: magazinevalidation_post.php');
exit();
In magazinevalidation_post.php file you can access the value with
<?php
session_start();
echo $_SESSION['first_name'];
echo $_SESSION['last_name']
echo $_SESSION['address'];
echo $_SESSION['city'];
echo $_SESSION['address'];
echo $_SESSION['zipcode'];
echo $_SESSION['months'];
?>

Insert statement not working PHP [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
The code below should get the input by the user and insert it into the customer table. However, i get the error :Problem with queryIncorrect integer value: 'customerid' for column 'customerID' at row 1. Can anyone help with this? Thanks
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Prac 2 Task 12</title>
</head>
<body>
<?php
$conn = mysql_connect("localhost", "user", "password");
mysql_select_db("factory291", $conn)
or die ('Database not found ' . mysql_error() );
$sql = "SELECT * FROM customer";
$rs = mysql_query($sql, $conn)
or die ('Problem with query' . mysql_error());
$ename = $elname = $ecus = $epcode = "";
$fnamecus = $lnamecus = $idcus = $pcde = "";
$error_report = false;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["customerid"])) {
$ecus = "Customer ID is required";
$error_report = true;
} else {
$idcus = input_t($_POST["customerid"]);
// check if numeric
if (preg_match("/[^0-9]/",$idcus)) {
$ecus = "Only numbers allowed";
$error_report = true;
}
if(strlen($idcus) != 6 && ($idcus) != null)
{
$ecus = "Customer ID must be 6 digits";
$error_report = true;
}
}
if (empty($_POST["customerfname"])) {
$ename = "First name is required";
$error_report = true;
} else {
$fnamecus= input_t($_POST["customerfname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-]*$/",$fnamecus)) {
$ename = "Only alphabetic letters and hyphen";
$error_report = true;
}
if(strlen($fnamecus) > 20 && ($fnamecus) != null)
{
$ename = "First name can't be more that 20 characters long";
$error_report = true;
}
}
if (empty($_POST["customerlname"])) {
$elname = "Last name is required";
$error_report = true;
} else {
$lnamecus = input_t($_POST["customerlname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-]*$/",$lnamecus)) {
$elname = "Only alphabetic letters and hyphen";
$error_report = true;
}
if(strlen($lnamecus) > 20 && ($lnamecus) != null)
{
$elname = "Last name can't be more that 20 characters long";
$error_report = true;
}
}
if (!is_null($_POST["postcode"])) {
$pcde = input_t($_POST["postcode"]);
// check if name only contains letters and whitespace
if (preg_match("/[^0-9]/",$pcde)) {
$epcode = "Only numbers allowed";
$error_report = true;
}
if(strlen($pcde) != 4 && ($pcde) != null)
{
$epcode = "Post code must be 4 digits";
$error_report = true;
}
}
}
if($error_report != true) {
$query="INSERT INTO customer (customerID, firstName, lastName, Address, suburb, state, postcode)
VALUES ('".$_POST['customerid']."', '".$_POST['customerfname']."', '".$_POST['customerlname']."',
'".$_POST['customeraddress']."', '".$_POST['suburb']."',
'".$_POST['state']."', '".$_POST['postcode']."')";
echo "correct";
}
function input_t($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h1>Customer Information Collection <br /></h1>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" id="custinfo" >
<table>
<tr>
<td><label for="customerid">Customer ID (integer value): </label></td>
<td><input type="text" id="customerid" name="customerid" size=11 value="<?php
echo $idcus;?>"/><span class="error">* <?php echo $ecus;?></span></td>
</tr>
<tr>
<td><label for="customerfname">Customer Frist Name: </label></td>
<td><input type="text" id="customerfname" name="customerfname" size=50 value="<?php
echo $fnamecus;?>"/><span class="error">* <?php echo $ename;?></span></td>
</tr>
<tr>
<td><label for="customerlname">Customer Last Name: </label></td>
<td><input type="text" id="customerlname" name="customerlname" size=50 value="<?php
echo $lnamecus;?>"/><span class="error">* <?php echo $elname;?></span></td>
</tr>
<tr>
<td><label for="customeraddress">Customer Address: </label></td>
<td><input type="text" id="customeraddress" name="customeraddress" size=65/></td>
<td><label for="suburb"> Suburb: </label></td>
<td><input type="text" id="suburb" name="suburb"/></td>
</tr>
<tr>
<td>
State:<select name="state" id="state">
<option value="select">--</option>
<option value="ACT">ACT</option>
<option value="NSW">NSW</option>
<option value="NT">NT</option>
<option value="QLD">QLD</option>
<option value="SA">SA</option>
<option value="TAS">TAS</option>
<option value="VIC">VIC</option>
<option value="WA">WA</option>
</select>
</td>
<td><label for="postcode"> Post Code: </label><input type="text" id="postcode"
name="postcode" size=4 value="<?php
echo $pcde;?>"/><span class="error"><?php echo $epcode;?></span></td>
</tr>
</table>
<p><input type="submit" value="Save Data"/> <input type="reset" value="Clear Form" />
</tr>
</form>
</body>
</html>
Your problem is incorrect use of quotes:
$query="INSERT INTO customer (customerID, firstName, lastName, Address, suburb, state, postcode)
VALUES ('customerid', 'customerfname', ‘customerlname', 'customeraddress', 'suburb',
'state', 'postcode')";
You are submitting the literal string values, 'customerid', etc.
From your code, it looks like you want to use the $_POST values, like this:
$query="INSERT INTO customer (customerID, firstName, lastName, Address, suburb, state, postcode)
VALUES ('".$_POST['customerid']."', '".$_POST['customerfname']."', '".$_POST['customerlname']."', '".$_POST['customeraddress']."', '".$_POST['suburb']."',
'".$_POST['state']."', '".$_POST['postcode']."')";
Also:
Please do not use the mysql_* functions. They are deprecated. Use MySQLi or PDO.
You are wide open to SQL injection. You need to escape your data or, even better, use prepared statements.

Server side validation and insertion to table

This php file is using server side validation via post method as the user enters data into the input devices. The only problem I'm having is inserting the data into the customers table as it doesn't work. I know this because i have created test php file that displays all the customer tables content and the data the user enters is not there. Where have i gone wrong?
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Prac 2 Task 12</title>
</head>
<body>
<?php
$conn = mysql_connect("localhost", "twa291", "......");
mysql_select_db("factory291", $conn)
or die ('Database not found ' . mysql_error() );
$sql = "SELECT * FROM customer";
$rs = mysql_query($sql, $conn)
or die ('Problem with query' . mysql_error());
$ename = $elname = $ecus = $epcode = "";
$fnamecus = $lnamecus = $idcus = $pcde = "";
$error_report = false;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["customerid"])) {
$ecus = "Customer ID is required";
$error_report = true;
} else {
$idcus = input_t($_POST["customerid"]);
// check if numeric
if (preg_match("/[^0-9]/",$idcus)) {
$ecus = "Only numbers allowed";
$error_report = true;
}
if(strlen($idcus) != 6 && ($idcus) != null)
{
$ecus = "Customer ID must be 6 digits";
$error_report = true;
}
}
if (empty($_POST["customerfname"])) {
$ename = "First name is required";
$error_report = true;
} else {
$fnamecus= input_t($_POST["customerfname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-]*$/",$fnamecus)) {
$ename = "Only alphabetic letters and hyphen";
$error_report = true;
}
if(strlen($fnamecus) > 20 && ($fnamecus) != null)
{
$ename = "First name can't be more that 20 characters long";
$error_report = true;
}
}
if (empty($_POST["customerlname"])) {
$elname = "Last name is required";
$error_report = true;
} else {
$lnamecus = input_t($_POST["customerlname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-]*$/",$lnamecus)) {
$elname = "Only alphabetic letters and hyphen";
$error_report = true;
}
if(strlen($lnamecus) > 20 && ($lnamecus) != null)
{
$elname = "Last name can't be more that 20 characters long";
$error_report = true;
}
}
if (!is_null($_POST["postcode"])) {
$pcde = input_t($_POST["postcode"]);
// check if name only contains letters and whitespace
if (preg_match("/[^0-9]/",$pcde)) {
$epcode = "Only numbers allowed";
$error_report = true;
}
if(strlen($pcde) != 4 && ($pcde) != null)
{
$epcode = "Post code must be 4 digits";
$error_report = true;
}
}
}
if($error_report != true) {
$query="INSERT INTO customer (customerID, firstName, lastName, Address, suburb, state, postcode)
VALUES ('customerid', 'customerfname', ‘customerlname', 'customeraddress', 'suburb',
'state', 'postcode')";
$queryResult = mysql_query($query, $conn)
or die ('Problem with query' . mysql_error());
echo "correct";
}
function input_t($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h1>Customer Information Collection <br /></h1>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" id="custinfo" >
<table>
<tr>
<td><label for="customerid">Customer ID (integer value): </label></td>
<td><input type="text" id="customerid" name="customerid" size=11 value="<?php
echo $idcus;?>"/><span class="error">* <?php echo $ecus;?></span></td>
</tr>
<tr>
<td><label for="customerfname">Customer Frist Name: </label></td>
<td><input type="text" id="customerfname" name="customerfname" size=50 value="<?php
echo $fnamecus;?>"/><span class="error">* <?php echo $ename;?></span></td>
</tr>
<tr>
<td><label for="customerlname">Customer Last Name: </label></td>
<td><input type="text" id="customerlname" name="customerlname" size=50 value="<?php
echo $lnamecus;?>"/><span class="error">* <?php echo $elname;?></span></td>
</tr>
<tr>
<td><label for="customeraddress">Customer Address: </label></td>
<td><input type="text" id="customeraddress" name="customeraddress" size=65/></td>
<td><label for="suburb"> Suburb: </label></td>
<td><input type="text" id="suburb" name="suburb"/></td>
</tr>
<tr>
<td>
State:<select name="state" id="state">
<option value="select">--</option>
<option value="ACT">ACT</option>
<option value="NSW">NSW</option>
<option value="NT">NT</option>
<option value="QLD">QLD</option>
<option value="SA">SA</option>
<option value="TAS">TAS</option>
<option value="VIC">VIC</option>
<option value="WA">WA</option>
</select>
</td>
<td><label for="postcode"> Post Code: </label><input type="text" id="postcode"
name="postcode" size=4 value="<?php
echo $pcde;?>"/><span class="error"><?php echo $epcode;?></span></td>
</tr>
</table>
<p><input type="submit" value="Save Data"/> <input type="reset" value="Clear Form" />
</tr>
</form>
</body>
</html>
You need to call mysql_query on your $query -- right now you're just defining the $query object and then ignoring it for the rest of the page.
Add something like the following on the line before echo "correct";
$queryResult = mysql_query($query, $conn)
or die ('Problem with query' . mysql_error());
n.b. I'll echo #Ozmah's comment about looking into PDO or mysqli functions - learning the deprecated plain mysql functions will be of dubious value.

PHP form validation

Below is my script that inserts data into a table. My question is only concerning form validations in php.
Here is my php code:
<?php
//Here I have defined an error variable for each of the variables in the project
$nameErr = $productErr = $priceErr = $catErr = $regionErr = "";
$product_name = $product_cond = $product_price = $product_cat = $product_region = "";
$con=mysqli_connect("localhost","*****","*****","my_project");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// here in this elseif, I check the number of characters in the field and then it is suppose to send an error (on the same page) if it does not match
elseif (strlen($_POST['product_name']) < 5 ) {
$productErr = "name is too short";
}
elseif (strlen($_POST['product_name']) > 10) {
$productErr = "name is too long";
}
elseif (empty($_POST['product_cond'])) {
$productErr = "product condition required";
}
else
{
$sql= "INSERT INTO Product (product_name, product_cond, product_price, product_cat, product_region, email, phone_num)
VALUES
('$_POST[product_name]','$_POST[product_cond]','$_POST[product_price]','$_POST[product_cat]','$_POST[product_region]','$_POST[Email]','$_POST[PhoneNumber]')";
if (!mysqli_query($con,$sql))
{
echo 'Error: ' . mysqli_error($con);
}
else
{
echo "1 record added";
}
}
mysqli_close($con);
?>
and here is my html page:
<html>
<body>
<h3> Please enter your product information bellow: </h3>
<form action="insert_data.php" method="post">
Product name: <input type="text" name="product_name" >
// here I added this line that is suppose to do echo the error message:
<span class="error">* <?php echo $nameErr;?></span>
Condition:
<select name="product_cond">
<option value="" >SELECT</option>
<option value="Used" >Used </option>
<option value="new" >New</option>
</select>
Category:
<select name="product_cat">
<option value="" >SELECT</option>
<option value="books" >books</option>
<option value="Computers" >Computers</option>
<option value="Hardware/Tools" >Hardware/Tools </option>
<option value="Cars" >Cars</option>
<option value="home Appliances" >home Appliances</option>
</select>
Region:
<select name="product_region">
<option value="Oulu" >Oulu</option>
<option value="Turku" >Turku</option>
<option value="Helsinki" >Helsinki </option>
<option value="Tornio" >Tornio</option>
<option value="Tampere" >Tampere</option>
<option value="Kemi" >Kemi</option>
</select>
Product price: <input type="text" name="product_price">
<input type="submit">
</form>
</body>
</html>
The problem is that this method still prevents the data to be inserted into the table but it does not give me an error instead, it just gives me a blank screen. What is the problem.
(I'm using this example provided by w3school: http://www.w3schools.com/php/showphp.asp?filename=demo_form_validation_required)
Try below code in php:
<?php
$con=mysqli_connect("localhost","*****","*****","my_project");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$error = false;
$errorMsg = "";
if (strlen($_POST['product_name']) < 5 ) {
$error = true;
$errorMsg. = "name is too short";
}
elseif (strlen($_POST['product_name']) > 10) {
$error = true;
$errorMsg. = "name is too long";
}
if (empty($_POST['product_cond'])) {
$error = true;
$errorMsg. = "product condition required<br/>";
}
if (empty($_POST['product_price'])) {
$error = true;
$errorMsg. = "product price required<br/>";
}
if (empty($_POST['product_cat'])) {
$error = true;
$errorMsg. = "product category required<br/>";
}
if (empty($_POST['product_region'])) {
$error = true;
$errorMsg. = "product region required<br/>";
}
if (empty($_POST['email'])) {
$error = true;
$errorMsg. = "email required<br/>";
}
if (empty($_POST['phone_num'])) {
$error = true;
$errorMsg. = "phone required<br/>";
}
if(!$error)
{
$sql= "INSERT INTO Product (product_name, product_cond, product_price, product_cat, product_region, email, phone_num)
VALUES ('$_POST[product_name]','$_POST[product_cond]','$_POST[product_price]','$_POST[product_cat]','$_POST[product_region]','$_POST[Email]','$_POST[PhoneNumber]')";
if (!mysqli_query($con,$sql))
{
echo 'Error: ' . mysqli_error($con);
}
else
{
echo "1 record added";
}
}else{
echo $errorMsg;
}
mysqli_close($con);
?>
PHP CODE
<?php
//Here I have defined an error variable for each of the variables in the project
if (isset($_POST['product_name']) && isset($_POST['product_cond']) && isset($_POST['product_price']) && isset($_POST['product_cat']) && isset($_POST['product_region']) && isset($_POST['Email']) && isset($_POST['PhoneNumber'])) {
$nameErr = $productErr = $priceErr = $catErr = $regionErr = "";
$product_name = $product_cond = $product_price = $product_cat =
$product_region = "";
$con = mysqli_connect("localhost", "*****", "*****", "my_project");
if
(mysqli_connect_errno()
) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// here in this elseif, I check the number of characters in the
field and then it is suppose to send an error(on the same page) if it
does not match
elseif (strlen($_POST['product_name']) < 5) {
$productErr = "name is too short";
} elseif (strlen($_POST['product_name']) > 10) {
$productErr = "name is too long";
} elseif (empty($_POST['product_cond'])) {
$productErr = "product condition required";
}
else {
$sql = "INSERT INTO Product (product_name, product_cond, product_price, product_cat, product_region, email, phone_num)
VALUES
('$_POST['product_name']','$_POST['product_cond']','$_POST['product_price']','$_POST['product_cat']','$_POST['product_region']','$_POST['Email']','$_POST['PhoneNumber']')";
if (!mysqli_query($con, $sql)) {
echo 'Error: ' . mysqli_error($con);
} else {
echo "1 record added";
} } mysqli_close($con);
}
?>
HTML
<html>
<body>
<h3> Please enter your product information bellow: </h3>
<form action="insert_data.php" method="post">
Product name: <input type="text" name="product_name" pattern="[a-zA-Z]{4,9}" required>
// here I added this line that is suppose to do echo the error message:
<span class="error">* <?php echo $nameErr;?></span>
Condition:
<select name="product_cond" required>
<option value="" >SELECT</option>
<option value="Used" >Used </option>
<option value="new" >New</option>
</select>
Category:
<select name="product_cat" required>
<option value="" >SELECT</option>
<option value="books" >books</option>
<option value="Computers" >Computers</option>
<option value="Hardware/Tools" >Hardware/Tools </option>
<option value="Cars" >Cars</option>
<option value="home Appliances" >home Appliances</option>
</select>
Region:
<select name="product_region" required>
<option value="Oulu" >Oulu</option>
<option value="Turku" >Turku</option>
<option value="Helsinki" >Helsinki </option>
<option value="Tornio" >Tornio</option>
<option value="Tampere" >Tampere</option>
<option value="Kemi" >Kemi</option>
</select>
Product price: <input type="text" name="product_price" pattern="[0-9]{0,5}" required>
<input type="submit">
</form>

this is concerning PHP and form validations

bellow you see my form validation script that I have been working on for a while. The script is suppose to check if the "Name:" is first not empty and then if it only contains letters and then insert the data. Likewise for the "Price:" it is suppose to check if it is not empty and then it's only digits. So far I have failed to make all the functions working and here are the problems as it sits right now:
in general it does not insert data to the table
regardless says price is required (even if the price is given)
when there is given numbers in the name field, there is no error
and here is the script:
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
$con=mysqli_connect("localhost","xxxxx","xxxxx","my_project");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// define variables and set to empty values
$nameErr = $priceErr = $catErr = $condErr = $regionErr = "";
$product_name = $product_price = $product_cat = $product_cond = $product_region = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["product_name"]))
{
$nameErr = "Name is required";
}
else if (!preg_match("/^[a-zA-Z ]*$/",$product_name))
{
$nameErr = "Only letters and white space allowed";
}
if (empty ($_POST ["product_price"]))
{
$priceErr = "Price is required";
}
else if(!ctype_digit($product_price))
{
$priceErr = "Price is required";
}
else
{
$product_name = test_input($_POST["product_name"]);
$product_price = test_input($_POST["product_price"]);
$sql= "INSERT INTO Product (product_name, product_cond, product_price, product_cat, product_region, email, phone_num)
VALUES
('$_POST[product_name]','$_POST[product_cond]','$_POST[product_price]','$_POST[product_cat]','$_POST[product_region]','$_POST[Email]','$_POST[PhoneNumber]')";
if (!mysqli_query($con,$sql))
{
echo 'Error: ' . mysqli_error($con);
}
else
{
echo "1 record added";
}
mysqli_close($con);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="product_name" value="<?php echo $product_name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
price: <input type="text" name="product_price" value="<?php echo $product_price;?>">
<span class="error">* <?php echo $priceErr;?></span>
<br><br>
Condition:
<select name="product_cond" required >
<option value="" >SELECT</option>
<option value="Used" >Used </option>
<option value="new" >New</option>
</select>
Category:
<select name="product_cat" required >
<option value="" >SELECT</option>
<option value="books" >books</option>
<option value="Computers" >Computers</option>
<option value="Hardware/Tools" >Hardware/Tools </option>
<option value="Cars" >Cars</option>
<option value="home Appliances" >home Appliances</option>
</select>
Region:
<select name="product_region" required >
<option value="" >SELECT</option>
<option value="Oulu" >Oulu</option>
<option value="Turku" >Turku</option>
<option value="Helsinki" >Helsinki </option>
<option value="Tornio" >Vaasa</option>
<option value="Tampere" >Tampere</option>
<option value="Kemi" >Kemi</option>
<input type="submit">
</form>
</body>
and here is the example that I have used and modified:
http://www.w3schools.com/php/showphp.asp?filename=demo_form_validation_special
I'd suggest to use an array of errors instead of variables.
Then you should access the variables you send by the form like $_POST['variable']
Try this code:
$errors = array();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["product_name"])) {
$errors['name'] = "Name is required";
} else if (!preg_match("/^[a-zA-Z ]*$/", $_POST['product_name'])) {
$errors['name'] = "Only letters and white space allowed";
}
if (empty($_POST ["product_price"])) {
$errors['price'] = "Price is required";
} else if (!ctype_digit($_POST['product_price'])) {
$errors['price'] = "Price is required";
}
if(count($errors) == 0){
$product_name = test_input($_POST["product_name"]);
$product_price = test_input($_POST["product_price"]);
$sql = "INSERT INTO Product (product_name, product_cond, product_price, product_cat, product_region, email, phone_num)
VALUES
('$_POST[product_name]','$_POST[product_cond]','$_POST[product_price]','$_POST[product_cat]','$_POST[product_region]','$_POST[Email]','$_POST[PhoneNumber]')";
if (!mysqli_query($con, $sql)) {
echo 'Error: ' . mysqli_error($con);
} else {
echo "1 record added";
}
}
}

Categories