Friday, October 31, 2008

PHP Forms

Important link for all your php needs: php.net

For PHP forms you can use either the GET or POST parameters; alternately the REQUEST parameter will both GET and POST.

If somebody submits a form without entering any information, you can send them back to the form like so:

if (empty($fullName)) { //empty is a built-in php function
header("Location:forms.html"); //special HTTP header
}

You can also send an alert once they have been returned to the main form:

if (empty($fullName)) { //empty is a built-in php function
header("Location:forms.php?error=true"); //special HTTP header
}


In the body, you can put:

<?php if($hasError): ?> //: is an alternative to { } offered in php ?>
<p><? = $errorMessage ?></p>
<?php endif ?>


In the php section put:

<?php

$hasError = false; //initially false on first visit because they have not clicked submit yet
if ($_REQUEST['error'] == 'true') { //error is the name or key
$errorMessage = "Please enter something";
$hasError = true; //sets the flag to true
}
?>

No comments: