Quick and Easy way to Parse and Process your html web forms
One of the most discussed topic in every web programming language is to parse and fetch form fields and process them in an easy way. Because nearly in 90% projects we use html web forms. Sometimes when you have large number of form fields, it is difficult to fetch and parse every field in short code. Here is a quick tip to do this for newbies.
-
Define your web form
First of all create and define your form elements. I am using five fields to work in this example. This code will parse all the form fields easily and can also retain the values of every field if there is any error handling process or if you want to keep the values inside fields.
<form method="post" action=""> <label for="name">Full Name:</label> <input type="text" name="name" id="name" value="<?php echo $form_vars['name']; ?>" /> <br /> <label for="email">Your Email:</label> <input type="text" name="email" id="email" value="<?php echo $form_vars['email']; ?>" /> <br /> <label for="loc">Location:</label> <input type="text" name="loc" id="loc" value="<?php echo $form_vars['loc']; ?>" /> <br /> <label for="passwd">Password:</label> <input type="password" name="passwd" id="passwd" value="<?php echo $form_vars['passwd']; ?>" /> <br /> <label for="repasswd">Retype Password:</label> <input type="text" name="repasswd" id="repasswd" value="<?php echo $form_vars['repasswd']; ?>" /> <br /> <input type="submit" name="sbt-form" value="Submit" /> </form>
-
Create PHP to parse form
Now put the following php code on top of your page.
<?php if(isset($_POST['sbt-form'])){ $form_fields = array("name","email","loc","passwd","repasswd"); $form_vars = array(); foreach($form_fields as $field){ $form_vars[$field] = isset($_POST[$field]) ? $_POST[$field] : ""; } unset($form_fields); } ?>At first we check if form is submitted or not. Then an array is created which holds names of every form element as field. Array elements must be the name of those fields whose values we need to process and parse. Then we loop though this array and fine all those form elements in HTTP_POST variable, if an element is not set or have blank value, the array element will still be created. You can process validation on form_vars variable per your needs. Even if the page is refreshed, your form will retain its field values. This is quickest and dirty simple code I always use to parse my long web forms.
Related posts
If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.







Great article!!!