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

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Louis8
    New Member
    • Mar 2007
    • 8

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

    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["postcommen t"]) != ""
    && (!isset($nameer ror) && (!isset($commen terror)))) {
    $posttitle = addslashes(trim (strip_tags($_P OST["posttitle"])));[/PHP]

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

    [PHP]form action="<?=$_SE RVER["PHP_SELF"]?>" method="post" id="addcomment" >
    <input type="hidden" name="post_id" value="<?=$post _id ?>" />
    <input type="hidden" name="posttitle " value="<?=$titl e ?>" />

    <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["postcommen t"]) != "" && (isset($nameerr or))) { ?>
    <span class="warning" ><?php echo $nameerror['name']; ?></span>
    <?php } ?><input name="name" type="text" <?php if(isset($comme nterror)
    && (isset($_POST["postcommen t"]) != "" && (!isset($nameer ror))))
    {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.
  • Louis8
    New Member
    • Mar 2007
    • 8

    #2
    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

    Comment

    • ronverdonk
      Recognized Expert Specialist
      • Jul 2006
      • 4259

      #3
      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:

      Code:
      -  check if the form is submitted
      -  if so:
         -  verify the submitted values
         -  when value omitted or blank: set a message in the $error array
         -  when no errors found, continue db processing and exit script
         -  when errors found, display all errors 
         -  continue form display with correct fields shown in form
      -  if not:
         - display the form
      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($_P OST["posttitle"])));
      // insert your record here
      exit;
      }

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

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

      [/php]

      Ronald :cool:

      Comment

      • Louis8
        New Member
        • Mar 2007
        • 8

        #4
        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....an d 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_con nect.php");

        // get post_id from query string
        $post_id = (isset($_REQUES T["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(pos tdate, '%M %e, %Y at %l:%i %p') AS dateattime FROM blg_posts
        WHERE post_id=$post_i d LIMIT 1";
        $result = mysql_query($sq l);
        $myposts = mysql_fetch_arr ay($result);
        }

        include ("functions.php ");

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

        $sql = "INSERT INTO comments
        (post_id,name,e mail,website,co mment)
        VALUES ('$post_id', '$name', '$email', '$website', '$comment')";
        $result2 = mysql_query($sq l);
        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: ".$posttitl e;
        $emailbody = "Comment on '".$posttitle." '"."\r\n"
        ."http://www.newnycrossr oads.com/post.php?post_i d=".$post_id
        ."#c".$comment_ id."\r\n\r\n"
        .$comment."\r\n \r\n"
        .$name." (".$website.")\ r\n\r\n";
        $emailbody = stripslashes($e mailbody);
        $emailheader = "From: ".$name." <".$email.">\r\ n"."Reply-To: ".$email;
        @mail("info@new nycrossroads.co m", $emailsubject, $emailbody, $emailheader);
        // direct to post page to eliminate repeat comment posts
        header("Locatio n: post.php?post_i d=$post_id&mess age=$message");
        }
        }

        if ($myposts) {
        $sql = "SELECT comment_id, name, website, comment, DATE_FORMAT(tst amp, '%M %e, %Y at %l:%i %p') AS commentdate FROM comments WHERE post_id = $post_id ORDER by tstamp DESC";
        $result3 = mysql_query($sq l);
        $mycomments = mysql_fetch_arr ay($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>$dateattim e</h4>\n";
        echo "<div class='post'>\n $post \n</div>";
        } while ($myposts = mysql_fetch_arr ay($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($mycomme nts["comment"]);
        $commentdate = ($mycomments["commentdat e"]);
        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>$comme nt</dd>\n";
        } while ($mycomments = mysql_fetch_arr ay($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("search form.php"); ?>

        <!-- Comment Submission form -->

        <form action="<?=$_SE RVER["PHP_SELF"]?>" method="post" id="addcomment" >
        <input type="hidden" name="post_id" value="<?=$post _id ?>" />
        <input type="hidden" name="posttitle " value="<?=$titl e ?>" />

        <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="postcomme nt" value="Post comment" /></p>
        </form>

        <!--END comment form -->



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

        </div>
        <!-- END Maincontent


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

        </body>
        </html>[/PHP]

        Comment

        • ronverdonk
          Recognized Expert Specialist
          • Jul 2006
          • 4259

          #5
          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:

          Comment

          • Louis8
            New Member
            • Mar 2007
            • 8

            #6
            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....beca use 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"....whic h 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

            Comment

            • ronverdonk
              Recognized Expert Specialist
              • Jul 2006
              • 4259

              #7
              Only way to find out is to show your code. And enclose the code within [php] and [/php ] tags.

              Ronald :cool:

              Comment

              • Louis8
                New Member
                • Mar 2007
                • 8

                #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_con nect.php");

                // get post_id from query string
                $post_id = (isset($_REQUES T["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(pos tdate, '%M %e, %Y at %l:%i %p') AS dateattime FROM blg_posts
                WHERE post_id=$post_i d LIMIT 1";
                $result = mysql_query($sq l);
                $myposts = mysql_fetch_arr ay($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($_P OST["posttitle"])));
                $name = addslashes(trim (strip_tags($_P OST["name"])));
                $email = addslashes(trim (strip_tags($_P OST["email"])));
                $website = addslashes(trim (strip_tags($_P OST["website"])));
                $comment = addslashes(trim (strip_tags($_P OST["comment"])));

                $sql = "INSERT INTO comments
                (post_id,name,e mail,website,co mment)
                VALUES ('$post_id', '$name', '$email', '$website', '$comment')";
                $result2 = mysql_query($sq l);
                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: ".$posttitl e;
                $emailbody = "Comment on '".$posttitle." '"."\r\n"
                ."http://www.newnycrossr oads.com/post.php?post_i d=".$post_id
                ."#c".$comment_ id."\r\n\r\n"
                .$comment."\r\n \r\n"
                .$name." (".$website.")\ r\n\r\n";
                $emailbody = stripslashes($e mailbody);
                $emailheader = "From: ".$name." <".$email.">\r\ n"."Reply-To: ".$email;
                @mail("info@new nycrossroads.co m", $emailsubject, $emailbody, $emailheader);
                // direct to post page to eliminate repeat comment posts
                header("Locatio n: post.php?post_i d=$post_id&mess age=$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>',$er rors);
                print '</b></li></ul></span>'; }
                }

                if ($myposts) {
                $sql = "SELECT comment_id, name, website, comment, DATE_FORMAT(tst amp, '%M %e, %Y at %l:%i %p') AS commentdate FROM comments WHERE post_id = $post_id ORDER by tstamp DESC";
                $result3 = mysql_query($sq l);
                $mycomments = mysql_fetch_arr ay($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>$dateattim e</h4>\n";
                echo "<div class='post'>\n $post \n</div>";
                } while ($myposts = mysql_fetch_arr ay($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($mycomme nts["comment"]);
                $commentdate = ($mycomments["commentdat e"]);
                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>$comme nt</dd>\n";
                } while ($mycomments = mysql_fetch_arr ay($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("search form.php"); ?>

                <!-- Comment Submission form -->

                <form action="<?=$_SE RVER["PHP_SELF"]?>" method="post" id="addcomment" >
                <input type="hidden" name="post_id" value="<?=$post _id ?>" />
                <input type="hidden" name="posttitle " value="<?=$titl e ?>" />

                <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="postcomme nt" value="Post comment" /></p>
                </form>

                <!--END comment form -->



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

                </div>
                <!-- END Maincontent


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

                </body>
                </html>[/PHP]

                Comment

                • devsusen
                  New Member
                  • Feb 2007
                  • 136

                  #9
                  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.

                  Code:
                  <script type="text/javascript">
                  
                  function validate_addcomment(frm) {
                    var value = '';
                    qfMsg = '';
                  
                    value = frm.elements['aname'].value;
                    if (value == '') {
                      qfMsg = qfMsg + '\n - Name is required';
                    }
                  
                    value = frm.elements['comment'].value;
                    if (value == '') {
                      qfMsg = qfMsg + '\n - Comment is required.';
                    }
                  
                    if (qfMsg != '') {
                      qfMsg = 'Invalid information.' + qfMsg;
                      qfMsg = qfMsg + '\nPlease correct these fields.';
                      alert(qfMsg);
                      return false;
                    }
                    return true;
                  }
                  
                  </script>
                  
                  <form action="<?=$_SERVER["PHP_SELF"]?>" method="post" id="addcomment" onsubmit="return validate_addcomment(this);">
                  <input type="hidden" name="post_id" value="<?=$post_id ?>" />
                  <input type="hidden" name="posttitle" value="<?=$title ?>" />
                  <h3>Add a comment</h3>
                  <p>Name: (Required)<br /><input name="aname" 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)<br /><textarea name="comment"  cols="25" rows="15">
                  </textarea></p>
                  <p><input type="submit" name="postcomment" value="Post comment"  /></p>
                  </form>
                  susen

                  Comment

                  • Louis8
                    New Member
                    • Mar 2007
                    • 8

                    #10
                    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.

                    Comment

                    • devsusen
                      New Member
                      • Feb 2007
                      • 136

                      #11
                      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.

                      Code:
                              <!-- 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>";
                      }
                      
                      if(isset($_POST['postcomment'])) {
                              $name = isset($_POST['name'] && $_POST['name'] != "")? $_POST['name'] : "";
                              $comment = isset($_POST['comment'] && $_POST['comment'] != "")? $_POST['comment'] : "";
                              $name_Err = ($name == "") ? "name is required" : "";
                              $comment_Err = ($comment == "") ? "comment required" : "";
                              if($name_Err == "" || $comment_Err == "") {
                                  // code to store the comment in database.
                              }
                      }
                      else  {
                              $name = "";
                              $comment = "";
                              $name_Err = "";
                              $comment_Err = "";
                      }
                      ?>
                          <p>Name: (Required) <?php echo $name_Err; ?>
                          <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)   <?php echo $comment_Err; ?>
                          <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 -->
                      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

                      Comment

                      • Louis8
                        New Member
                        • Mar 2007
                        • 8

                        #12
                        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($mis sing, $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="'.htmle ntities($_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="'.htmle ntities($_POST['email']).'"'; } ?> /></p>[/PHP]

                        Comment

                        Working...