php_discipulus Posted May 14, 2013 Share Posted May 14, 2013 I just made this form in php (nowhere near finished) that checks for user input in the form, if there is no input it gives an error, if there is input and the user submits a form no previous entered data is lost, So what you think is this correct? Can I improve it in anyway? <?php $missing = array(); if (isset($_POST['send'])) { $to = 'myemail@example.com'; $subject = 'Form subject'; $expected = array('name', 'email', 'comment'); $required = array('name', 'email', 'comment'); foreach($_POST as $key => $value) { // Assign to temp var to value $temp = (is_array($value)) ? $value : trim($value); // Store empty values in missing array if (empty($temp) && in_array($key, $required)) { $missing[] = $key; } elseif (empty($temp) && in_array($key, $expected)) { ${$key} = $temp; } } // If you find something missing // keep the same value of user input $name = $_POST['name']; $email = $_POST['email']; $comment = $_POST['comment']; } ?> <form method="post" action=""> <p> <label for="name">Enter your name:</label><br> <input type="text" name="name" id="name" value="<?php if(!empty($value) && !(in_array('name', $missing))) { echo $name; } ?>" /> <?php if (in_array('name', $missing)) { echo "You missed out your name"; } ?> </p> <p> <label for="email">Enter your email:</label><br> <input type="text" name="email" id="email" value="<?php if(!empty($value) && !(in_array('email', $missing))) { echo $email; } ?>" /> <?php if (in_array('email', $missing)) { echo "You missed out your email"; } ?> </p> <p> <label for="email">Enter comment:</label><br> <textarea name="comment" id="comment" cols="40" rows="10"><?php if(!empty($value) && !(in_array('comment', $missing))) { echo $comment; } ?></textarea> <?php if (in_array('comment', $missing)) { echo "You missed out your comment"; } ?> </p> <p> <input type="submit" name="send" id="send" value="Send" /> </p> </form> Quote Link to comment Share on other sites More sharing options...
Q695 Posted May 15, 2013 Share Posted May 15, 2013 do $_POST['send']!='' for all the variables. Quote Link to comment Share on other sites More sharing options...
mac_gyver Posted May 15, 2013 Share Posted May 15, 2013 Can I improve it in anyway? The form itself should be dynamically produced by looping over the $expected array. The $expected array may need to be expanded to hold unique information about each field, such as the field type. Quote Link to comment Share on other sites More sharing options...
Q695 Posted May 15, 2013 Share Posted May 15, 2013 tie the back end into a database that populates the form based on numbers, and text. On the back end have it do a for each output, and hidden if the variables are filled in, but others are blank. I did one of those a few years ago. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.