Page 1 of 1

Required Fields on Forms - Almost There I Think...

Posted: Fri Sep 12, 2008 6:58 pm
by zunebuggy
I am new to PHP.

I have a simple HTML form. When a user clicks Submit it will do the following: <FORM METHOD="POST" ACTION="whatever.php">

I want my whatever.php script to check the fields from the form (they are ALL required) and if any are NULL, I would like it to return back to the HTML form and display a message on the form telling them what fields need to be taken care of.

Right now I have a form at http://www.mydomain.com/register.html (for example). I have heard you can have a PHP script that actually creates the form dynamically and can display error messages. I can sort of picture how to do this, but my register page is a link (/register.html) off from my home page. It does not seem logical or correct to me to have a link to register.php that generates a register.html. But I might be wrong...

So I really have two questions here:
1). Should I create my form dynamically with PHP?
2). Can someone give an example of the correct way to redirect or re-create the form page based on a missing field? I think I have the beginnings here, correct?

Code: Select all

 
if ($username == "")
{ //redirect back to register.html or create new form dynamically
}
 
if ($password == "")
{ //...
}
 

Re: Required Fields on Forms - Almost There I Think...

Posted: Fri Sep 12, 2008 8:24 pm
by JAB Creations
1.) I highly recommend reading this page for a minimal of thirty seconds...
index.php

...once you do you'll know why many of the regulars here get annoyed at code posts in the General Discussion forum. :|

2.) Easy as cake question which I'm glad I'm able to be the one helping someone else out.

XHTML

Code: Select all

<form action="" method="get">
<input name="example_get" value="juice" />
</form>
PHP

Code: Select all

<?php
echo $_GET['example_get']; //will echo juice
?>
XHTML

Code: Select all

<form action="" method="post">
<input name="example_post" value="fruit" />
</form>
PHP

Code: Select all

<?php
echo $_POST['example_post']; //will echo fruit
?>
As far as I am concerned working examples trump five useless pages of explanations. :)

Re: Required Fields on Forms - Almost There I Think...

Posted: Fri Sep 12, 2008 8:30 pm
by Christopher
Vivid examples, but the OP was about checking fields an showing error messages.
zunebuggy wrote:So I really have two questions here:
1). Should I create my form dynamically with PHP?
You don't need to create the HTML dynamically. But yes, you should use PHP.
zunebuggy wrote:2). Can someone give an example of the correct way to redirect or re-create the form page based on a missing field? I think I have the beginnings here, correct?
Instead use http://www.mydomain.com/register.php and have it submit the form to itself. Check to see if the values are set in $_POST and not empty strings. Redisplay the form with error messages if there are errors. Process the data and then redirect if all fields are ok.