Jump to content

if submitted process form, else show form


keeps21

Recommended Posts

Hi

 

Is there an easier way to write this pseudo code script so that I don’t have to write the form out twice?

 

At the moment I have separated the form html into a separate script and I'm just doing an include to call it in.

 

if   { // form has been submitted

      // process form

      if { //error when processing form 

      // output error   
      // show form (include form.html)

      }

} else { // form hasn’t been submitted

      //show form (include form.html)

}

 

Thanks for any advice.

 

Stephen

Link to comment
Share on other sites

<?php
// basic form and form processing code -

// condition the inputs and setup default values -
$submitted = isset($_POST['submit']) ? $_POST['submit'] : FALSE; // was the form submitted?
$name_field = isset($_POST['name']) ? $_POST['name'] : ""; // condition the form's name field

if($submitted) {
$form_error = array(); // array to hold any form validation errors

// validate the form data here (set elements in $form_error to hold error messages)
	if(empty($name_field)) {
	$form_error[] = "Please fill in the name";
}

// if there were no form validation errors, use the data that was submitted
if(empty($form_error)) {
	// do something with the data here
	echo "The name you entered was: $name_field";
}
}

// display the form if it has not been submitted or there are form validation errors
If(!$submitted || !empty($form_error)) {
// check for and display any form validation errors
if(!empty($form_error)) {
	echo "Please correct these errors -<br />";
	foreach($form_error as $error) {
		echo "$error<br />";
	}
}

// display the form, with any previously submitted values
?>
<form method="post" action="">
Name: <input type="text" name="name" value="<?php echo $name_field; ?>">
<input type="submit" name="submit">
</form>
<?php
}
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.