Outputting error messages

I am working on an html order form that has some Javascript validation, and uses PHP to send the order by email to the administrator, with a copy to the purchaser. I also am ‘trying’ to use PHP to validate the form. I have almost no experience in PHP, and some experience in Javascript coding.

As a result, most of the PHP code I am using I have borrowed and adapted from elsewhere, but I do understand what it is doing and was able to add some of my own successfully.

My problem is getting the error messages to show up instead of $error. I have included the relevant code (the middle part is part of the form processing so I left it out because it works like a charm). The only thing that doesn’t seem to be responding is the last statement echo $error;

I am too inexperienced to be able to figure out what I have done wrong here, so I was wondering if someone could help. Please be patient if it was a stupid mistake that I couldn’t see. :blush:

$errors = '';

if (empty($_POST['fullname'])  || 
	empty($_POST['campername'])  || 
   empty($_POST['phone']) || 
   empty($_POST['email']))
{
    $errors .= "\
 Error: all fields are required";
}

	$fullname = $_POST['fullname'];
	$campername = $_POST['campername'];
	$phone = $_POST['phone'];
	$email = $_POST['email'];

if (!eregi(
"^[_a-z0-9-]+(\\.[_a-z0-9-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,3})$", 
$email))
{
    $errors .= "\
 Error: Invalid email address";
}
.
.
.
.
.
.
.
	if( empty($errors))
{
    //redirect to the 'thank you' page
   header('Location: thankyou.html');

	// Email message sent to administrator with a copy to the purchaser
	$message = <<<EOD
<br/><hr/><br/>
Name: $fullname <br/>
Camper's Name: $campername <br/>
Phone Number: $phone <br/>
Email Address: $email <br/>
<p>The following items were ordered:<br/>
$purchase<br/><br/>
Total Payment Due: $totalAmt</p>
Comments: $comments<br /><br />
$fullname will $payment the payment<br/>
and pick up the order at $pickup date.<br/>
EOD;

	$headers = "From: $email\\r\
";
	$headers .= "Content-type: text/html\\r\
";
	$headers .= "Cc: $email \\r\
";
	mail($webMaster, $emailSubject, $message, $headers);
} 	
echo $errors;

I didn’t see it in your code examples, but my first thought was that the variable was inside single quotes (non-parsed) instead of double quotes (parsed).

Maybe you changed quotes during your fix attempts?

In any case, glad it’s OK now.

And I guess you should get a new FTP client :smiley:

You’re on the right path, start small and build up your skills. I recently looked at some code I wrote seven years ago, and it was quite comical.

Yes, please post the rest of the code. The code you posted doesn’t show the source of the problem. We can all guess at how/what the rest of the code is doing, but without knowing exactly what’s going on, we’ll just send you on wild goose chases trying to track down the problem.

Also, is the HTML form display and validation all on the form.php page? Or are there different page redirects involved?

Edit:

Actually, since you’re saying the screen is outputting “$error”, is it possible that you have embedded the PHP variable in some HTML code?

e.g.:

<div>$error</div>

instead of:

<div><?php echo $error;?></div>

I agree. That’s why I want to make the PHP validation work.

Thanks for all your responses.

My problem is that I am just starting to learn server-side scripting, so it has to be as straightforward as possible for me to understand it well enough to troubleshoot it, although I was able to add some of my own code to it with success. I have taken one introductory college-level course in Javascript and did extremely well, so I don’t feel intimidated with coding … just a little in over my head right now where PHP is concerned.

The output I am getting is $error, not the value of $error. Would it help if I posted the entire PHP script? I left out the middle part because it really wasn’t relevant to the problem.

Thanks for excluding the confidential information in the post . . . I wish half the people at work were smart enough to do that. :wink:

The code posted has the variable $errors (with an ‘s’). Is it displaying $error (without an ‘s’)? If so, and it’s not a typo, then the problem is elsewhere.

Is the first sentence saying that the code is outputting the variable name, “$errors”, instead of the content of the variable? Not outputting “echo $errors”, just “$errors”?

The code you posted does not contain any semantic (logic) errors. Assuming that at least one of those fields is blank, or the email address is invalid, the last statement should execute since $errors will be a non-empty string.

What happens when the form does not validate? There might be something in the code you omitted that, although it works, does something that is preventing the last statement from executing.

Could you also post the HTML form?
Not the complete HTML, just the part starting with <form> and ending with </form> :slight_smile:

Just a guess based on your code:


if (isset($_POST['submit'])) {

	$error = FALSE;
	$error_note = '';

	// Check empty fields
	if ( empty($_POST['field1'])  || empty($_POST['field2'])) {
		// Error is found (TRUE), create the notice
		$error = TRUE;
		$error_note = "\
 Error: all fields are required";
	} 

	// Fields are filled, now validate them
	if ( $error === FALSE ) { 	
		// Example - email:
		// Check for valid email	
		if ( email_checking_function_against( $_POST['email'] ) ) ) {
			$error = TRUE;
			$error_note = "\
 Error: Invalid email address";
		} else {
			$email = $_POST['email'];	
		}
	
	}

	if( $error === TRUE ) {
		echo $error_note;
	} else {
		//redirect to the 'thank you' page
		header('Location: thankyou.html');
		// other stuff omitted...
	} 

}

If you are already using Javascript, then I would use Javascript to check the empty fields.

Here is another guess using Jquery:


$(document).ready( function() {
	$('#post').submit( function() {
		// Error note
		var note = '<span class="error">This field is empty</span>';
		// No errors yet...
		var error = false;
		// define our field values			
		var inp1 = $('input#field1');
		var inp2 = $('input#field2');			
		// Throw it all in a array
		var fields = [inp1, inp2];
		
		// If the error is already present, remove it
		$('.error').remove();
		
		// Validate
		for (var i in fields){	
			if (fields[i].val() == '') {
				error = true; // we have an true error, redefine the variable
				$(fields[i]).after(note); // Put the error note after the input element
			}
		}
								
		if (error === true){
			return false; // stop the form submitting
		} else {
			// all fields are entered, now let's validate it
			additional_form_check_in_js();
		}
	});
});	

The typo was in my sitepoint post, not the code. I did have $errors.

The strange thing is that now I am getting the correct error message, but I’m not sure what I changed. I suspect it might have been caused by incorrect uploading of the file, because I have been having a few issues with my FTP client and this website … not overwriting the old file correctly, and even sometimes adding the new file on to the end of the old file. I do know that in the last upload, I deleted the other files first.

Thanks so much for your help … I guess the problem is solved now.

Here’s the form. I just removed any contact information that was on it.

<form id = "orderform"  action = "form.php" method = "post">
				<table>
					<tr id = "infofield">
						<td>
							<fieldset id = "personalInfo">
								<legend>Personal Information</legend>
					
								<div class = "label">
									<label for = "fullname">Full Name:</label> 
									<input type = "text" size = "30" maxlength = "40" id = "fullname" name = "fullname" onblur = "validateNonEmpty(this);"/>
								</div>
						
								<div class = "label">								
									<label for = "campername">Camper's Name:</label>
									<input type = "text" size = "30" maxlength = "40" id = "campername" name = "campername" onblur = "validateNonEmpty(this);"/>
								</div>
						
								<div class = "label">
									<label for = "phone">Phone Number:</label>
									<input type = "text" size = "30" maxlength = "40" id = "phone" name = "phone" onblur = "validateNonEmpty(this);"/>
								</div>						
							
								<div class = "label">
									<label for = "email">Email Address: </label>
									<input type = "text" size = "30" maxlength = "40" id = "email" name = "email" onblur = "validateNonEmpty(this);"/>
								</div>
							</fieldset>
						</td>
						<td>
							<img src = "images/logoAlone.png" id = "image" width = "150" height = "150" alt = "Kwasind logo" />
						</td>
						
					</tr>
									
					<tr id = "orderfield">
					
						<td colspan ="2">
							
								<fieldset  id = "order">
								
									<h2 id = "orderInstructions">Enter the quantity of each item that you would like to order:</h2>
									
									<legend>Order</legend>
													
									<div id = "miscellaneous">
					
									<h2>Miscellaneous Items</h2>
					
									<div class = "item">
										<label for = "stuffedBear">Cuddles, the Stuffed Bear ... $12</label>
										<input type = "text" size = "2" maxlength = "5" id = "stuffedBear" name = "stuffedBear" onchange = "updateOrder();" />
									</div>
						
									<div class = "item">				
										<label for = "stuffedMoose">Monti, the Stuffed Moose ... $12</label>
										<input type = "text"  size = "2" maxlength = "5"  id = "stuffedMoose" name = "stuffedMoose" onchange = "updateOrder();" />
									</div>
						
									<div class = "item">
										<label for = "ecoPen">Eco-Friendly Pen ... $1.50 ea.</label>
										<input type = "text" size = "2" maxlength = "5"  id = "ecoPen" name = "ecoPen" onchange = "updateOrder();" />
										</div>
							
									<div class = "item">						
										<label for = "frisbee">Frisbee (assorted colours) ... $3 ea.</label>
										<input type = "text" size = "2" maxlength = "5"  id = "frisbee" name = "frisbee" onchange = "updateOrder();" />
									</div>
							
									<div class = "item">
										<label for = "lantern">Mini Lantern ... $12</label>
										<input type = "text" size = "2" maxlength = "5" id = "lantern" name = "lantern" onchange = "updateOrder();" />
									</div>		
								
									<div class = "item">
										 <label for = "zipperPull">Paddle Zipper Pull ... $3 ea.</label>
										<input type = "text" size = "2" maxlength = "5"  id = "zipperPull"  name = "zipperPull" onchange = "updateOrder();" />
									</div>
								
									<div class = "item">
										<label for = "redWaterBottle">Water Bottle (red) ... $10</label>
										<input type = "text" size = "2" maxlength = "5"  id = "redWaterBottle" name = "redWaterBottle" onchange = "updateOrder();" />
									</div>
				
									<div class = "item">
										<label for = "blueWaterBottle">Water Bottle (blue) ... $10</label>
										<input type = "text" size = "2" maxlength = "5"  id = "blueWaterBottle" name = "blueWaterBottle" onchange = "updateOrder();" />
									</div>
								
									<div class = "item">
										<label for = "blueBlanket">Fleece Blanket (blue) ... $20</label>
										<input type = "text" size = "2" maxlength = "5"  id = "blueBlanket" name = "blueBlanket" onchange = "updateOrder();" />
									</div>	
								
									<div class = "item">
										<label for = "redBlanket">Fleece Blanket (red) ... $20</label>
										<input type = "text" size = "2" maxlength = "5"  id = "redBlanket"  name = "redBlanket" onchange = "updateOrder();" />
									</div>	
								</div>
								
								<div id = "clothing">
							
									<h2>Shirts and Hoodies</h2>
				
									<div class = "item">
										<label for ="blackBucketballShirt">Bucketball Shirt (black) ... $20</label>
										<input type = "text" size = "2" maxlength = "5"  id ="blackBucketballShirt" name ="blackBucketballShirt" onchange = "updateOrder();" />
									</div>	
							
									<div class = "item">					
										<label for = "whiteBucketballShirt"> Bucketball Shirt (white) ... $20</label>
										<input type = "text" size = "2" maxlength = "5"  id = "whiteBucketballShirt" name = "whiteBucketballShirt" onchange = "updateOrder();" />
									</div>
							
									<div class = "item">
										<label for = "kwasindShirt"> Shirt ... $12</label>
										<input type = "text" size = "2" maxlength = "5"  id = "kwasindShirt" name = "kwasindShirt" onchange = "updateOrder();" />
									</div>		
									
									<div class = "item">
										<label for = "paddleShirt">Paddle Shirt ... $20</label>
										<input type = "text" size = "2" maxlength = "5"  id = "paddleShirt" name = "paddleShirt" onchange = "updateOrder();" />
									</div>		
									
									<div class = "item">					
										<label for = "shakeitShirt">"Shake It" Shirt ... $15</label>
										<input type = "text" size = "2" maxlength = "5"  id = "shakeitShirt" name = "shakeitShirt" onchange = "updateOrder();" />
									</div>
									
									<div class = "item">
										<label for = "vintageShirt">Vintage T-Shirt ... $20</label>
										<input type = "text" size = "2" maxlength = "5"  id = "vintageShirt" name = "vintageShirt" onchange = "updateOrder();" />
									</div>
													
									<div class = "item">
										<label for = "blackHoodie">Hoodie ... $35</label>
										<input type = "text" size = "2" maxlength = "5"  id = "blackHoodie" name = "blackHoodie" onchange = "updateOrder();" />
									</div>
								
									<div class = "item">
										<label for = "vintageHoodie">Vintage Hoodie ... $35</label>
										<input type = "text" size = "2" maxlength = "5"  id = "vintageHoodie" name = "vintageHoodie" onchange = "updateOrder();" />
									</div>
									<div id = "back">
									<h2><a href = "KwasindStoreTest.html">Return to images</a></h2>
									</div>
								</div>
								
								<div id = "commentSection">
									<label for = "comments">Comments:</label><br/>
									<div id = "commentArea">
										<textarea cols = "0" rows = "3" id = "comments" name = "comments"></textarea>
									</div>
								</div>
								
							</fieldset>
							
						</td>
						
					</tr>
					<tr id = "totalfield">
							<td>
							<fieldset id = "orderPayment">
								<legend>Payment and Pickup</legend>
								
								<div id = "paymentOptions">
									Method of payment:<br />
									<input type = "radio" checked = "checked" name = "payment" id = "mail" value = "mail"/>I will mail my cheque to ***********.<br />
									<input type = "radio" name = "payment" id = "deliver" value = "deliver"/>I will bring my payment to ******************.<br />
									<span id = "note">Note: cheques must be made payable to <em>************</em>.</span>
								</div>
								<div id = "pickupOptions">
									Pick up order:<br />
									<input type = "radio" checked = "checked" name = "pickup" id ="campday" value = "kickoff"/>I will pick up the items on ****************<br />
									<input type = "radio" name = "pickup" id = "earlyday" value = "early" />I will arrange to pick items up from ****************.<br />
								</div>
							
							</fieldset>
						</td>
					
						<td>
							<fieldset id = "total">
								<legend>Order Summary</legend>
								<p>See how much you have spent:</p>
																		
								<div class = "label">
									<label for = "totalAmt">Total:</label>
									<input type = "text" size = "10" maxlength = "40" id = "totalAmt" name = "totalAmt"/>
								</div>
								
								<div id = "buttons">
								<input type="submit" value="Submit Order" id = "submit" name = "submit" /> 
									<input type="reset" value="Reset" id = "reset" name = "reset" /> 
								</div>
							
							</fieldset>
						</td>
					
					</tr>
					
				</table>
				
			</form >

No, I have the PHP code in a separate file. Here is the complete code, including an extra error message I have added since which outputs a message if nothing has been selected from the order list. My error message works, because I just echoed the string, but the other validation part that I borrowed from a tutorial is what doesn’t work.

I have replaced the client name and email address with ******. Everything else is unchanged.

<?php

$errors = '';

if (empty($_POST['fullname'])  || 
	empty($_POST['campername'])  || 
   empty($_POST['phone']) || 
   empty($_POST['email']))
{
    $errors .= "\
 Error: all fields are required";
}

	$fullname = $_POST['fullname'];
	$campername = $_POST['campername'];
	$phone = $_POST['phone'];
	$email = $_POST['email'];

if (!eregi ("^[_a-z0-9-]+(\\.[_a-z0-9-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,3})$", $email))
{
    $errors .= "\
 Error: Invalid email address";
}


/* Subject and email variables */

	$emailSubject = '**********';
	$webMaster = '*********@*****.com';
	
/* Gathering Data Variables */

	$stuffedBear = array('stuffed bear', $_POST['stuffedBear']);
	$stuffedMoose = array('stuffed moose', $_POST['stuffedMoose']);
	$ecoPen =  array('eco-friendly pen', $_POST['ecoPen']);
	$frisbee =  array('frisbee', $_POST['frisbee']);
	$lantern =  array('lantern', $_POST['lantern']);
	$zipperPull =  array('zipper pull', $_POST['zipperPull']);
	$redWaterBottle =  array('red water bottle', $_POST['redWaterBottle']);
	$blueWaterBottle =  array('blue water bottle', $_POST['blueWaterBottle']);
	$blueBlanket =  array('blue fleece blanket', $_POST['blueBlanket']);
	$redBlanket =  array('red fleece blanket', $_POST['redBlanket']);
	$blackBucketballShirt =  array('black bucketball shirt', $_POST['blackBucketballShirt']);
	$whiteBucketballShirt =  array('white bucketball shirt', $_POST['whiteBucketballShirt']);
	$kShirt = array('orangeshirt', $_POST['kwasindShirt']);
	$paddleShirt =  array('paddle shirt', $_POST['paddleShirt']);
	$shakeitShirt =  array('shake it shirt', $_POST['shakeitShirt']);
	$vintageShirt =  array('vintage shirt', $_POST['vintageShirt']);
	$blackHoodie =  array('black hoodie', $_POST['blackHoodie']);
	$vintageHoodie =  array('vintage hoodie', $_POST['vintageHoodie']);
	
	$itemList = array($stuffedBear, $stuffedMoose, $ecoPen, $frisbee, $lantern, $zipperPull, $redWaterBottle, $blueWaterBottle, $blueBlanket, $redBlanket, 
								$blackBucketballShirt, $whiteBucketballShirt, $kShirt, $paddleShirt, $shakeitShirt, $vintageShirt, $blackHoodie, $vintageHoodie);
	$j = 0;
	$purchase = '';
	for ($i= 0; $i < count($itemList); $i++) 
	{
		if ($itemList[$i][1] != 0)
		{
		$purchase = $purchase . '<br/>' . $itemList[$i][0] . ' - ' . $itemList[$i][1];
		}
	}
	if ($purchase == '')
	{
	echo 'Please choose some items for your order.';
	}
	else
	{
	$payment = $_POST['payment'];
	/* two values - mail and deliver*/
	$pickup = $_POST['pickup'];
	/* two values - kickoff and early */

	$comments = $_POST['comments'];
	$totalAmt = $_POST['totalAmt'];
	$submit = $_POST['submit'];
	$reset = $_POST['reset'];
	
	if( empty($errors))
{
    //redirect to the 'thank you' page
   header('Location: thankyou.html');

	// Email message sent to administrator with a copy to the purchaser
	$message = <<<EOD
<br/><hr/><br/>
Name: $fullname <br/>
Camper's Name: $campername <br/>
Phone Number: $phone <br/>
Email Address: $email <br/>
<p>The following items were ordered:<br/>
$purchase<br/><br/>
Total Payment Due: $totalAmt</p>
Comments: $comments<br /><br />
$fullname will $payment the payment<br/>
and pick up the order at $pickup date.<br/>
EOD;

	$headers = "From: $email\\r\
";
	$headers .= "Content-type: text/html\\r\
";
	$headers .= "Cc: $email \\r\
";
	mail($webMaster, $emailSubject, $message, $headers);
} 	
	echo $errors;
}
?>



You can’t rely on just the client-side to validate forms. Sure using client-side validation to off-load the server is a good thing, but some users have javascript disabled / a browser that is not capable of processing javascript, which allows them to post anything they like if you don’t do additional server-side checking.