O'Reilly logo

Learning PHP 5 by David Sklar

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Form Processing with Functions

The basic form in Example 6-1 can be made more flexible by putting the display code and the processing code in separate functions. Example 6-6 is a version of Example 6-1 with functions.

Example 6-6. Saying "Hello" with functions

// Logic to do the right thing based on 
// the submitted form parameters
if (array_key_exists('my_name',$_POST) {
    process_form( );
} else {
    show_form( );
}

// Do something when the form is submitted
function process_form( ) {
    print "Hello, ". $_POST['my_name'];
}

// Display the form
function show_form( ) {
    print<<<_HTML_
<form method="POST" action="$_SERVER[PHP_SELF]">
Your name: <input type="text" name="my_name">
<br/>
<input type="submit" value="Say Hello">
</form>
_HTML_;
}

To change the form or what happens when it's submitted, change the body of process_form( ) or show_form( ). These functions make the code a little cleaner, but the logic at the top still depends on some form-specific information: the my_name parameter. We can solve that problem by using a hidden parameter in the form as the test for submission. If the hidden parameter is in $_POST , then we process the form. Otherwise, we display it. In Example 6-7, this strategy is shown using a hidden parameter named _submit_check.

Example 6-7. Using a hidden parameter to indicate form submission

// Logic to do the right thing based on // the hidden _submit_check parameter if ($_POST['_submit_check']) { process_form( ); } else { show_form( ); } // Do something when ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required