PHP I : Forms

Creating a Form

Follow this lesson in Ullman Chapter 3. The scripts are located in the 03 directory.

See the page feedback.html described on Ullman pages 44ff.

Be especially careful to note the value of form action!

  • Use GET to GET unaltered data.
  • Use POST to POST new data to (usually) a database.
  • HTML:
    <INPUT TYPE=TEXT NAME=first_name SIZE=20>
  • XHTML:
    <input type=”text” name=”first_name” size=”20″ />

    Please complete this form to submit your feedback: <br />
    <form action=”handle_form.php” method=”post”>
    ….

    Name: <input type=”text” name=”name” size=”20″ />
    <br />
    Email Address: <input type=”text” name=”email” size=”20″ value=”anonymous”/>
    // Note how to assign a default value above.
    <br />
    ….

    Comments: <textarea name=”comments” rows=”3″ cols=”30″></textarea>
    <br />
    <input type=”submit” name=”submit” value=”Send My Feedback” />
    </form>

 

Handling Submitted Data

See the page handle_form.php described on Ullman pages 52ff.

This section in particular requires that register globals is ON in your PHP.INI file.

 

$name
$email
$title

<?php
print “Thank you $name for your comments. <br />”;
print “You … added: $comments”;
?>

From here on out, forget about accessing variables this way.

 

Displaying Error Messages

In PHP.INI:

display_errors = ON
// The value can be ON or OFF.

Within a script:

ini_set (‘display_errors’, 1);
// 1 is on, 0 is off.

Add this line to your php template.

 

Setting Error Reporting Level

Within a script:

error_reporting (E_ALL & ~ E_NOTICE);

Add this line to your php template. (See script_03_06\handle_form.php for usage.)

 

Superglobals

$_POST

$_GET

 

<?php

ini_set (‘display_errors’, 1);
error_reporting (E_ALL & ~ E_NOTICE);

// This is how to do it when register_globals is off.
print “Thank you {$_POST[‘title’]} {$_POST[‘name’]} for your comments. <br />”;

….

?>

 

See script_03_07\handle_form.php for a detailed example of using superglobals.

The critical point is that the form method (GET or POST) must match the superglobal you use ($_POST or $_GET).

Compare $_POST and $_GET with $HTTP_POST_VARS and $HTTP_GET_VARS. In what version of PHP did the former replace the latter?

 

The “GET” Trick

View the page hello.php in your browser.

Now add this to the end of the URL:

?name=Fred

 

To do for this section:

Create, for your own demonstration site, your own detailed example of submitting forms, accessing their information and displaying that information.

Be sure to link these pages to your index.htm.

 

To do out of class:

Review Chapter 3 of Ullman.