Php validation return error to user

Hello again, thank you to all who have helped. I have another question. I have been trying to validate the data entered by the user on the backend of my website. It will give me an error stating that they have not typed in any data however, I would like the pPrice to be an integer with two decimal place.
The product Name should contain only white space and letters. I had the validation for the product name working and now it is not. Because of this I am thinking I am not understand or using the ‘else’ ‘elseif’ functions properly.

My code:

<?php
  define('ALLOW_ACCESS', 1); //define a constant to give permission to use include files
	$title = 'Add a product';
	require('../../incAdmin/incHead.php');
	require_once('../../incAdmin/adminConnect.php');
?>
<h2>Add a new product to the Leas Japan Art</h2>  
<?php
if ($_SESSION['loggedIn']) {

if (isset($_POST['cmdSubmit'])) {
  // CREATE VARIABLES from form's POST data
  $categoryID = $_POST['cboCategoryID'];
  $productID = $_POST['txtProductID'];
  $pName = $_POST['txtName'];
  $pDate = $_POST['txtDate'];
  $pSize = $_POST['txtSize'];
  $pPrice = $_POST['txtPrice'];
  $pImage = $_POST['txtImage'];
  $pDesc = $_POST['txtDesc'];
  

  // VALIDATE THE FORM (this is very basic - you could make the validation more comprehensive)
  $message = '';

  if (empty($productID)) {
	$message = "ERROR: Please enter a product ID number";
  }
  if (empty($pName)) {
	$message = $message . "\nERROR: Please enter the product name";
  }
  elseif (!preg_match('/^[a-zA-Z ]+$/',$pName)) {
     $message = "\nERROR: Only letters and white space allowed in Product Name"; 
  }
   if (empty($pDesc)) {
	$message = $message . "\nERROR: Please enter the product description";
  }
  if (empty($pImage)) {
	$message = $message . "\nERROR: Please enter the file address for the image";
  }
  if (empty($pPrice)) {
	$message = $message . "\nERROR: Please enter the product price";
  }
  elseif (!is_int ($pPrice)){
	  $message = $message . "\nERROR: Please enter a number with two decimal places";
  }
  
  $sql = "INSERT INTO products (productID, pName, pPrice, pImage) VALUES ('$productID','$pName','$pPrice','$pImage')";
	if ($stmt = $db->prepare($sql)) {
	 	$stmt->execute();
		$stmt->close();
	 	$message = 'Record has successfully been added to database';
	}
	else {
		// an error has occurred, so the statement wasn't executed
		print 'Database error while attempting to add record: ' . $db->error;	
    	}
  
}
else {  // this is the first time form will be displayed. Initialise variables.
    $categoryID = '';
    $productID = '';
    $pName = '';
	$pDate = '';
	$pSize = '';
    $pPrice = '';
    $pImage = 'placeholder.jpg';
	$pDesc = '';
    $message = '';

}


?>
<form id="frmAddProduct" method="post" action="addProduct.php">
  <p><br />
  	<label>Category:</label>
	<select name="cboCategoryID">
	    	<?php
			//Set up a drop-down list of categories
			$stmt = $db->prepare('SELECT * FROM category ORDER BY cName');
			$stmt->execute();
			$stmt->bind_result($OUTPUTcategoryID, $OUTPUTcName);
			// while setting up the drop-down list, retain any PREVIOUSLY SELECTED option
			while ($stmt->fetch() ) {
				print '<option ';
				if ($OUTPUTcategoryID == $categoryID) { print 'selected '; }
				print 'value="';
				print $OUTPUTcategoryID;
				print '">';
				print $OUTPUTcName;
				print '</option>';
			}
			$stmt->close();
	    	?>
	</select>
	<br /><br />
  	
  	<label>Product ID :</label>
	<input type="text" name="txtProductID" id="txtProductID" size="8" value="<?php print $productID; ?>" />
  	<br /><br />
  	<label>Product Name:</label> 
	<input type="text" name="txtName" id="txtName" size="70" value="<?php print $pName; ?>" />
  	<br /><br />
	<label>Product Date:</label> 
	<input type="text" name="txtDate" id="txtDate" size="20" value="<?php print $pDate; ?>" />
  	<br /><br />
	<label>Product Size:</label> 
	<input type="text" name="txtSize" id="txtSize" size="40" value="<?php print $pSize; ?>" />
  	<br /><br />
	<label>Image filename:</label> 
	<input type="text" name="txtImage" id="txtImage" size="30" value="<?php print $pImage; ?>" />
 	 <em>(must include file extension, eg seascape.jpg)</em><br /><br />
   	<label>Product price: &#160;&#160;&#160; $</label> 
	<input type="text" name="txtPrice" id="txtPrice" size="8" value="<?php print $pPrice; ?>" />
 	 <br /><br />
	<label>Product Description:</label>
	<input type="text" name="txtDesc" id="txtDesc" size="150" value="<?php print $pDesc; ?>" />
  	<br /><br />
 


  	<input type="submit" name="cmdSubmit" id="cmdSubmit" value="Add record to database" />
  	<br /><br />
  
  	<label>Report:</label>
  	<textarea name="txtMessage" id="txtMessage" cols="60" rows="4" readonly="readonly"
		style="background-color:#FFF;color:#000; overflow:hidden;"><?php print $message;?></textarea>
  </p>
</form>
<!----------------------------------------------------------------------------->
<?php

}
else {
    	print 'ERROR: you are not authorised to access this page';
} 
require('../../incAdmin/incFoot.php');
?>

A couple of things. I’m not sure whether it completely answers your points.

I think you misunderstand what an integer is. An integer has NO decimal places so if you expect 2 decimal places it will never be an integer. You’re looking at a floating point number.

The other thing is that the recommended way to check if a form has been submitted is

if ( $_SERVER['REQUEST_METHOD'] == 'POST' )

not checking the submit button.

HTH
G

I haven’t a problem with the submit button in a long time, but in my opinion a better way in checking for user input is to create a hidden field.

<input type="hidden" name="action" value="cmdSubmit">

that way you can just do the following

if ( isset($_POST['action'])  && $_POST['action'] === 'cmdSubmit') {
  // Enter Code here`indent preformatted text by 4 spaces`
}

You still need a submit button but it bypass the problem of it not being recognized on older IE browsers and if you do it the server way at least do the following.

$`submit = filter_input(INPUT_SERVER, 'REQUEST_METHOD', FILTER_SANITIZE_URL)`;

of curse you should always sanitize $_POST as well.:wink:

Also, if you require the price to be a number with two decimal places, format it yourself. There’s nothing more annoying than filling out a form and having it reject “24” and make me type in “24.00” instead.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.