By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,680 Members | 1,666 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,680 IT Pros & Developers. It's quick & easy.

Advice on a PHP form submission/error msg solution I created

Louis8
P: 8
I would be very appreciative of anyone who could show me a better way to do what I did. Complete newbee here. I have a comment form sidebar of blog. I wanted to Name & Comment fields required and give error msgs when empty upon submit. AND wanted to make sure the comment wasn't lost in the event of an error. Here's what I did:


[PHP]
// Check to make sure Name & Comment are NOT empty
$name = trim($_POST['name']);
if (empty($name)) {
$nameerror['name'] = 'Please enter your name';
}

$comment = trim($_POST['comment']);
if (empty($comment)) {
$commenterror['comment'] = 'Please enter a comment';
}

// If comment submitted & post exists
//AND no error, then add comment to db
if (isset($_POST["postcomment"]) != ""
&& (!isset($nameerror) && (!isset($commenterror)))) {
$posttitle = addslashes(trim(strip_tags($_POST["posttitle"])));[/PHP]

Of course, I'm leaving off the other variables for space considerations...
Then in my form I did the following....and by some miracle it worked:

[PHP]form action="<?=$_SERVER["PHP_SELF"]?>" method="post" id="addcomment">
<input type="hidden" name="post_id" value="<?=$post_id ?>" />
<input type="hidden" name="posttitle" value="<?=$title ?>" />

<h3>Add a comment</h3>
<?php
if (isset($message)) {
echo "<p class='message'>".$_POST["message"]."</p>";
}
?>
<p>Name: (Required) <!-- Error msg inserted if NAME empty -->
<br />
<?php if (isset($_POST["postcomment"]) != "" && (isset($nameerror))) { ?>
<span class="warning"><?php echo $nameerror['name']; ?></span>
<?php } ?><input name="name" type="text" <?php if(isset($commenterror)
&& (isset($_POST["postcomment"]) != "" && (!isset($nameerror))))
{echo "value='$name'";} else {echo "value=''";} ?> /></p>[/PHP]


And I did the same for the Comment part. It seems so complicated for a simple concept. Does anyone have a better, more concise way or suggestion? Thanks a lot.
Mar 10 '07 #1
Share this Question
Share on Google+
11 Replies


Louis8
P: 8
Actually just discovered my solution doesn't work. when I press submit with Name and Comment fields empty....it auto populates with some other name...perhaps the name I had last entered. I've been working on this for 5 days and I'm completely lost. I just want to stop submission if Name and Comment are empty, deliver an error message for the field that is empty, retain the field in the event of an error (so users who forget name, don't have to retype the whole bloody comment.) and then I want it to clear the fields upon successful submision. Can anyone help?
Thank you
Mar 10 '07 #2

ronverdonk
Expert 2.5K+
P: 4,258
Welcome to TSDN!

Since you did not post all your code, I made a simple setup of the form and its processing. Basically all fields are checked, errors are stored in an array and the form is displayed with all correct fields. Like this:

Expand|Select|Wrap|Line Numbers
  1. -  check if the form is submitted
  2. -  if so:
  3.    -  verify the submitted values
  4.    -  when value omitted or blank: set a message in the $error array
  5.    -  when no errors found, continue db processing and exit script
  6.    -  when errors found, display all errors 
  7.    -  continue form display with correct fields shown in form
  8. -  if not:
  9.    - display the form
  10.  
Test it out and adapt it to your requirement
[php]
<?php
$errors = array();

// process values after submit
if (isset($_POST['submitted'])) {

// verify the name
if (isset($_POST['name']) AND trim(strip_tags($_POST['name'])) > ' ')
$name = trim(strip_tags($_POST['name']));
else
$errors[] = 'Please enter your name';

// verify the comments
if (isset($_POST['comment']) AND trim(strip_tags($_POST['comment'])) > ' ')
$comment = trim(strip_tags($_POST['comment']));
else
$errors[] = 'Please enter a comment';

// when no errors continue processing db task
if (!$errors) {
$posttitle = addslashes(trim(strip_tags($_POST["posttitle"])));
// insert your record here
exit;
}

// there were errors encounterd, show them and re-display the form
else {
print '<span style="color:red;">Please correct the following errors:<br />';
print '<ul><li><b>';
print implode('</b></li><li><b>',$errors);
print '</b></li></ul></span>';
}

} // End 'submitted' set
?>
<form action="<?=$_SERVER["PHP_SELF"]?>" method="post">
<input type="hidden" name="post_id" value="<?=$post_id ?>" />
<input type="hidden" name="posttitle" value="<?=$title ?>" />
<p>Name: (Required)<input type="text" name="name" value="<?php echo $name ?>" /><br />
<p>Comment: (Required)<input type="text" name="comment" value="<?php echo $comment ?>" /><br />
<p><input type="submit" name="submitted" value="submit" />
</form>

[/php]

Ronald :cool:
Mar 10 '07 #3

Louis8
P: 8
Bedankt Ronald. You are right, I should have provided my entire code. Here it is. I did what you said, and I understand putting the errors into an array and creating an if statement with !errors.....but I got a parse error with an unexpected "else" statement....and I'm so new to this that I figured I should have given you the whole code instead! What you're seeing is the code BEFORE I tried to get a validation of NAME and COMMENT fields and WITHOUT your previous suggestions. I desire to stop the form being accepted and an e-mail being sent if these are blank, and obviously do not want to update the db until the form is filled out. This is a comment form for a blog that is stored in my sidebar. Thanks for any further guidance. - Louis

[PHP]<?php
// open connection to database
include("db_connect.php");

// get post_id from query string
$post_id = (isset($_REQUEST["post_id"]))?$_REQUEST["post_id"]:"";

// if post_id is a number get post from database
if (preg_match("/^[0-9]+$/", $post_id)) {
$sql = "SELECT post_id, title, post, DATE_FORMAT(postdate, '%M %e, %Y at %l:%i %p') AS dateattime FROM blg_posts
WHERE post_id=$post_id LIMIT 1";
$result = mysql_query($sql);
$myposts = mysql_fetch_array($result);
}

include ("functions.php");

// If comment has been submitted and post exists then add comment to database
if (isset($_POST["postcomment"]) != "") {
$posttitle = addslashes(trim(strip_tags($_POST["posttitle"])));
$name = addslashes(trim(strip_tags($_POST["name"])));
$email = addslashes(trim(strip_tags($_POST["email"])));
$website = addslashes(trim(strip_tags($_POST["website"])));
$comment = addslashes(trim(strip_tags($_POST["comment"])));

$sql = "INSERT INTO comments
(post_id,name,email,website,comment)
VALUES ('$post_id', '$name', '$email', '$website', '$comment')";
$result2 = mysql_query($sql);
if (!$result2) {
$message = "Failed to insert comment.";
} else {
$message = "Comment added.";
$comment_id = mysql_insert_id();
// Send yourself an email when a comment is successfully added
$emailsubject = "Comment added to: ".$posttitle;
$emailbody = "Comment on '".$posttitle."'"."\r\n"
."http://www.newnycrossroads.com/post.php?post_id=".$post_id
."#c".$comment_id."\r\n\r\n"
.$comment."\r\n\r\n"
.$name." (".$website.")\r\n\r\n";
$emailbody = stripslashes($emailbody);
$emailheader = "From: ".$name." <".$email.">\r\n"."Reply-To: ".$email;
@mail("info@newnycrossroads.com", $emailsubject, $emailbody, $emailheader);
// direct to post page to eliminate repeat comment posts
header("Location: post.php?post_id=$post_id&message=$message");
}
}

if ($myposts) {
$sql = "SELECT comment_id, name, website, comment, DATE_FORMAT(tstamp, '%M %e, %Y at %l:%i %p') AS commentdate FROM comments WHERE post_id = $post_id ORDER by tstamp DESC";
$result3 = mysql_query($sql);
$mycomments = mysql_fetch_array($result3);
}

?>

<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>New NY Crossroads Blog</title>

<link rel="stylesheet" type="text/css" href="blog.css" />


</head>

<body>

<!-- BEGIN Header -->

<?php include("header.php"); ?>

<!-- END Header -->

<!-- This is main part of page -->
<div id="maincontent" >

<!-- POSTS -->
<!-- five most recent posts will go here -->
<div id="posts">
<?php
if($myposts) {
do {
$post_id = $myposts["post_id"];
$title = $myposts["title"];
$post = format($myposts["post"]);
$dateattime = $myposts["dateattime"];
echo "<h2>$title</h2>\n";
echo "<h4>$dateattime</h4>\n";
echo "<div class='post'>\n $post \n</div>";
} while ($myposts = mysql_fetch_array($result));
} else {
echo "<p>There is no post matching a post_id of $post_id.</p>";
}
?>

<!-- BEGIN Comments -->
<div id="comments">
<h2>Comments</h2>
<?php
if($mycomments) {
echo "<dl>";
do {
$comment_id = $mycomments["comment_id"];
$name = $mycomments["name"];
$website = $mycomments["website"];
$comment = format($mycomments["comment"]);
$commentdate = ($mycomments["commentdate"]);
if ($website != "") {
echo "<dt><a href='$website'>$name</a> wrote on $commentdate</dt>\n";
} else {
echo "<dt>$name wrote on $commentdate</dt>\n";
}
echo "<dd>$comment</dd>\n";
} while ($mycomments = mysql_fetch_array($result3));
echo "</dl>";
} else {
echo "<p>There are no comments yet.</p>";
}
?>
</div>
<!-- END Comments -->

</div>
<!-- END Posts -->


<!-- SIDEBAR -->
<div id="sidebar">
<br />
<p><a href="../index.php">New NY Crossroads - HOME</a></p>

<!-- Search -->

<?php include("searchform.php"); ?>

<!-- Comment Submission form -->

<form action="<?=$_SERVER["PHP_SELF"]?>" method="post" id="addcomment">
<input type="hidden" name="post_id" value="<?=$post_id ?>" />
<input type="hidden" name="posttitle" value="<?=$title ?>" />

<h3>Add a comment</h3>
<?php
if (isset($message)) {
echo "<p class='message'>".$_POST["message"]."</p>";
}
?>
<p>Name: (Required) <!-- I want an Error msg inserted if NAME empty -->
<br /><input name="name" type="text" /></p>

<p>Email: <input name="email" type="text" /></p>

<p>Website:
<br />http://<input name="website" type="text" class="web" /></p>

<p>Comment: (Required) <!-- I want an Error msg inserted if COMMENTempty -->
<br /><textarea name="comment" cols="25" rows="15">
</textarea></p>

<p><input type="submit" name="postcomment" value="Post comment" /></p>
</form>

<!--END comment form -->



</div>
<!-- END Sidebar -->

</div>
<!-- END Maincontent


<!-- FOOTER -->
<?php include("footer.php"); ?>

</body>
</html>[/PHP]
Mar 11 '07 #4

ronverdonk
Expert 2.5K+
P: 4,258
I provided you with the structure and the sample code of how to tackle this. You can now build your code using that structure and code.

Ronald :cool:
Mar 11 '07 #5

Louis8
P: 8
Thanks Ronald, I did follow your guidance. I created the $errors array, verified the form fields and followed the IF ELSE logic....I also did some research on IMPLODE....because I have no clue what that is. Now, when I post with one of the form fields empty, I get the error page.....but a list like this

Please correct the following errors:

xname
xmail
xcomment
Please enter your email


No matter what field I leave empty....I get the array values listed first then the actual error message.
The part I don't understand is why, when I fill in all fields, I still get the error like this: In other words. I can not successfully submit a comment yet.

Please correct the following errors:

xname
xmail
xcomment


I also can't understand why my comment form fields are still filled with past data when I enter the blog topic for the first time. Each time I revisit the blog entry, the comments form sections are still populated with the last entry's data! I've seen a large number of items similar to resetting forms on google, but the one I'm probably looking for is "Clear" ....not reset. I understand reset to mean "back to the original values"....which is not really what I want unless it's an error and I want to retain the already entered fields until the user corrects the missing parts.

If you can point me in the right direction of suggest what to read next....I would be very, very grateful. Thanks
-Louis
Mar 13 '07 #6

ronverdonk
Expert 2.5K+
P: 4,258
Only way to find out is to show your code. And enclose the code within [php] and [/php ] tags.

Ronald :cool:
Mar 13 '07 #7

Louis8
P: 8
Here is my code with the added suggestions Ronald gave. It does produce the error msgs when fields are empty, however, I can not post a comment now even when all fields are filled. Here is the updated code.


[PHP]<?php
// open connection to database
include("db_connect.php");

// get post_id from query string
$post_id = (isset($_REQUEST["post_id"]))?$_REQUEST["post_id"]:"";

// if post_id is a number get post from database
if (preg_match("/^[0-9]+$/", $post_id)) {
$sql = "SELECT post_id, title, post, DATE_FORMAT(postdate, '%M %e, %Y at %l:%i %p') AS dateattime FROM blg_posts
WHERE post_id=$post_id LIMIT 1";
$result = mysql_query($sql);
$myposts = mysql_fetch_array($result);
}

include ("functions.php");

$errors = array('xname', 'xmail', 'xcomment');

// Process values after submit
if (isset($_POST['postcomment'])) {

// Verify name
if (isset($_POST['name']) AND trim(strip_tags($_POST['name'])) > ' ')
$name = trim(strip_tags($_POST['name']));
else
$errors['xname'] = 'Please enter your name';

//Verify email
if (isset($_POST['email']) AND trim(strip_tags($_POST['email'])) > ' ')
$name = trim(strip_tags($_POST['email']));
else
$errors['xmail'] = 'Please enter your email';

//Verify comment
if (isset($_POST['comment']) AND trim(strip_tags($_POST['comment'])) > ' ')
$name = trim(strip_tags($_POST['comment']));
else
$errors['xcomment'] = 'Please enter a comment';

// If no errors, process the code
if (!$errors) { $posttitle = addslashes(trim(strip_tags($_POST["posttitle"])));
$name = addslashes(trim(strip_tags($_POST["name"])));
$email = addslashes(trim(strip_tags($_POST["email"])));
$website = addslashes(trim(strip_tags($_POST["website"])));
$comment = addslashes(trim(strip_tags($_POST["comment"])));

$sql = "INSERT INTO comments
(post_id,name,email,website,comment)
VALUES ('$post_id', '$name', '$email', '$website', '$comment')";
$result2 = mysql_query($sql);
if (!$result2) {
$message = "Failed to insert comment.";
} else {
$message = "Comment added.";
$comment_id = mysql_insert_id();
// Send yourself an email when a comment is successfully added
$emailsubject = "Comment added to: ".$posttitle;
$emailbody = "Comment on '".$posttitle."'"."\r\n"
."http://www.newnycrossroads.com/post.php?post_id=".$post_id
."#c".$comment_id."\r\n\r\n"
.$comment."\r\n\r\n"
.$name." (".$website.")\r\n\r\n";
$emailbody = stripslashes($emailbody);
$emailheader = "From: ".$name." <".$email.">\r\n"."Reply-To: ".$email;
@mail("info@newnycrossroads.com", $emailsubject, $emailbody, $emailheader);
// direct to post page to eliminate repeat comment posts
header("Location: post.php?post_id=$post_id&message=$message");
exit;
}
}
// There were errors found
else {
print '<span class="warning">Please correct the following errors:<br />';
print '<ul><li><b>';
print implode('</b></li><li><b>',$errors);
print '</b></li></ul></span>'; }
}

if ($myposts) {
$sql = "SELECT comment_id, name, website, comment, DATE_FORMAT(tstamp, '%M %e, %Y at %l:%i %p') AS commentdate FROM comments WHERE post_id = $post_id ORDER by tstamp DESC";
$result3 = mysql_query($sql);
$mycomments = mysql_fetch_array($result3);
}

?>

<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>New NY Crossroads Blog</title>

<link rel="stylesheet" type="text/css" href="blog.css" />


</head>

<body>

<!-- BEGIN Header -->

<?php include("header.php"); ?>

<!-- END Header -->

<!-- This is main part of page -->
<div id="maincontent" >

<!-- POSTS -->
<!-- five most recent posts will go here -->
<div id="posts">
<?php
if($myposts) {
do {
$post_id = $myposts["post_id"];
$title = $myposts["title"];
$post = format($myposts["post"]);
$dateattime = $myposts["dateattime"];
echo "<h2>$title</h2>\n";
echo "<h4>$dateattime</h4>\n";
echo "<div class='post'>\n $post \n</div>";
} while ($myposts = mysql_fetch_array($result));
} else {
echo "<p>There is no post matching a post_id of $post_id.</p>";
}
?>

<!-- BEGIN Comments -->
<div id="comments">
<h2>Comments</h2>
<?php
if($mycomments) {
echo "<dl>";
do {
$comment_id = $mycomments["comment_id"];
$name = $mycomments["name"];
$website = $mycomments["website"];
$comment = format($mycomments["comment"]);
$commentdate = ($mycomments["commentdate"]);
if ($website != "") {
echo "<dt><a href='$website'>$name</a> wrote on $commentdate</dt>\n";
} else {
echo "<dt>$name wrote on $commentdate</dt>\n";
}
echo "<dd>$comment</dd>\n";
} while ($mycomments = mysql_fetch_array($result3));
echo "</dl>";
} else {
echo "<p>There are no comments yet.</p>";
}
?>
</div>
<!-- END Comments -->

</div>
<!-- END Posts -->


<!-- SIDEBAR -->
<div id="sidebar">
<br />
<p><a href="../index.php">New NY Crossroads - HOME</a></p>

<!-- Search -->

<?php include("searchform.php"); ?>

<!-- Comment Submission form -->

<form action="<?=$_SERVER["PHP_SELF"]?>" method="post" id="addcomment">
<input type="hidden" name="post_id" value="<?=$post_id ?>" />
<input type="hidden" name="posttitle" value="<?=$title ?>" />

<h3>Add a comment</h3>
<?php
if (isset($message)) {
echo "<p class='message'>".$_POST["message"]."</p>";
}
?>
<p>Name: (Required) <!-- I want an Error msg inserted if NAME empty -->
<br /><input name="name" type="text" value="<?php echo $name ?>"/></p>

<p>Email: <input name="email" type="text" value="<?php echo $email ?>" /></p>

<p>Website:
<br />http://<input name="website" type="text" class="web" /></p>

<p>Comment: (Required) <!-- I want an Error msg inserted if COMMENTempty -->
<br /><textarea name="comment" cols="25" rows="15"><?php echo $comment ?> </textarea></p>

<p><input type="submit" name="postcomment" value="Post comment" /></p>
</form>

<!--END comment form -->



</div>
<!-- END Sidebar -->

</div>
<!-- END Maincontent


<!-- FOOTER -->
<?php include("footer.php"); ?>

</body>
</html>[/PHP]
Mar 14 '07 #8

100+
P: 136
Hi,

why don't you go for a client side validation for ur comment form. I am providing u a code, hope this will solve ur problem.

Expand|Select|Wrap|Line Numbers
  1. <script type="text/javascript">
  2.  
  3. function validate_addcomment(frm) {
  4.   var value = '';
  5.   qfMsg = '';
  6.  
  7.   value = frm.elements['aname'].value;
  8.   if (value == '') {
  9.     qfMsg = qfMsg + '\n - Name is required';
  10.   }
  11.  
  12.   value = frm.elements['comment'].value;
  13.   if (value == '') {
  14.     qfMsg = qfMsg + '\n - Comment is required.';
  15.   }
  16.  
  17.   if (qfMsg != '') {
  18.     qfMsg = 'Invalid information.' + qfMsg;
  19.     qfMsg = qfMsg + '\nPlease correct these fields.';
  20.     alert(qfMsg);
  21.     return false;
  22.   }
  23.   return true;
  24. }
  25.  
  26. </script>
  27.  
  28. <form action="<?=$_SERVER["PHP_SELF"]?>" method="post" id="addcomment" onsubmit="return validate_addcomment(this);">
  29. <input type="hidden" name="post_id" value="<?=$post_id ?>" />
  30. <input type="hidden" name="posttitle" value="<?=$title ?>" />
  31. <h3>Add a comment</h3>
  32. <p>Name: (Required)<br /><input name="aname" type="text" /></p>
  33. <p>Email: <input name="email" type="text"  /></p>
  34. <p>Website:<br />http://<input name="website" type="text"  class="web" /></p>
  35. <p>Comment: (Required)<br /><textarea name="comment"  cols="25" rows="15">
  36. </textarea></p>
  37. <p><input type="submit" name="postcomment" value="Post comment"  /></p>
  38. </form>
susen
Mar 14 '07 #9

Louis8
P: 8
Thanks Devsusen. I really appreciate you taking the time to help me. My first thoughts are this: I'd prefer to stay with PHP since I wouldn't have to deal with javascript being enabled, disabled, etc on the client side. I formed these opinions from the vast internet searching I do and the the postings that are out there. However, perhaps you can share with me your experience with javascript vs. PHP to further broaden my opinions. I'm totally open. I should tell you that I don't really use Javascript (read: "Don't have experience") for the reason I stated above. And I'm really committed to getting masterful at PHP....so I'd still prefer a PHP solution. But I do thank you for your contribution and I'm cutting and pasting your code to my library of "goodies". Thanks again.
Mar 15 '07 #10

100+
P: 136
Hi Louis8,

I also agreed with u that client side validation may not work if javascript is disabled in browser. But nowadays this possibility is decreasing very fast.

Ok, I can provide u server side script in PHP. I think this should work for u.

Expand|Select|Wrap|Line Numbers
  1.         <!-- Comment Submission form -->                    
  2. <form action="<?=$_SERVER["PHP_SELF"]?>" method="post" id="addcomment">
  3. <input type="hidden" name="post_id" value="<?=$post_id ?>" />
  4. <input type="hidden" name="posttitle" value="<?=$title ?>" />
  5. <h3>Add a comment</h3>
  6. <?php
  7. if (isset($message)) {
  8.   echo "<p class='message'>".$_POST["message"]."</p>";
  9. }
  10.  
  11. if(isset($_POST['postcomment'])) {
  12.         $name = isset($_POST['name'] && $_POST['name'] != "")? $_POST['name'] : "";
  13.         $comment = isset($_POST['comment'] && $_POST['comment'] != "")? $_POST['comment'] : "";
  14.         $name_Err = ($name == "") ? "name is required" : "";
  15.         $comment_Err = ($comment == "") ? "comment required" : "";
  16.         if($name_Err == "" || $comment_Err == "") {
  17.             // code to store the comment in database.
  18.         }
  19. }
  20. else  {
  21.         $name = "";
  22.         $comment = "";
  23.         $name_Err = "";
  24.         $comment_Err = "";
  25. }
  26. ?>
  27.     <p>Name: (Required) <?php echo $name_Err; ?>
  28.     <br /><input name="name" type="text" value="<?php echo $name ?>"/></p>
  29.     <p>Email: <input name="email" type="text" value="<?php echo $email ?>" /></p>
  30.     <p>Website: 
  31.         <br />http://<input name="website" type="text"  class="web" /></p>
  32.     <p>Comment: (Required)   <?php echo $comment_Err; ?>
  33.     <br /><textarea name="comment"  cols="25" rows="15"><?php echo $comment ?>            </textarea></p>
  34.     <p><input type="submit" name="postcomment" value="Post comment"  /></p>
  35.     </form>
  36.         <!--END comment form -->
The comment form, I have taken from ur code. Modified it and added the PHP code, so that it can work seemlessly in ur page.

susen
Mar 15 '07 #11

Louis8
P: 8
Thanks Susen and Ronald.

I probably used a combination of both your suggestions. The real problem is my lack of understanding. I used PHP Solutions by David Powers and the explanations are what I needed more than the code itself. I did end up using an array as Ronald suggested. I'll show the code for your information. Again. Thank you, both, for your attention and help. -Louis

[PHP]// list expected fields
$expected = array('name' , 'email', 'website', 'comment');
// set required fields
$required = array('name', 'email', 'comment');
// create empty array for missing fields
$missing = array();

// process the $_POST variables
foreach ($_POST as $key => $value) {
//assign to temp variable & strip whitespace is not an array
$temp = is_array($value) ? $value : trim($value);
// if empty and required, add to $missing array
if (empty($temp) && in_array($key, $required)) {
array_push($missing, $key);
}
// otherwise, assign to a variable of same name as $key
elseif (in_array ($key, $expected)) {
${key} = $temp;
}
}[/PHP]

Then in my comment form: in order to have field be blank initially, send errors for the required fields and to retain fields when error occurs, I did the following taken directly from the Mr. Powers' book. (I'm only including Name and email to save space)


[PHP]<p>Name: (Required) <!-- I want an Error msg inserted if NAME empty -->
<br /><?php if (isset($missing) && in_array('name', $missing)) { ?>
<span class="warning">Please enter your name</span><?php } ?>
<input name="name" type="text" <?php if (isset($missing)) {
echo 'value="'.htmlentities($_POST['name']).'"'; } ?> /></p>

<p>Email:
<br /><?php if (isset($missing) && in_array('email', $missing)) { ?>
<span class="warning">Please enter your email</span><?php } ?>
<input name="email" type="text" <?php if (isset($missing)) {
echo 'value="'.htmlentities($_POST['email']).'"'; } ?> /></p>[/PHP]
Mar 16 '07 #12

Post your reply

Sign in to post your reply or Sign up for a free account.