#native_company# #native_desc#
#native_cta#

Forms & Submission

By Brett Patterson
on June 27, 2005

Forms & Submission
Forms are used a lot, and with PHP you can do some pretty neat stuff. I am going to assume that you know how to create a valid HTML form, and just need help with the processing side of it. To get things started, let’s create a form:

<form action=”” method=”post”>
    Name: <input type=”text” name=”name”>
    Age: <input type=”text” name=”age”>
    <input type=”submit” name=”Submit” value=”I Love Chocolate”>
    <input type=”submit” name=”Submit” value=”I Hate Chocolate”>
    <input type=”submit” name=”Submit” value=”Chocolate = Zits”>
</form>

So we’ll start with some easy processing–we’ll get the name and age first:

<?php

$name = $_POST[‘name’];
$age = $_POST[‘age’];

?>

Easy right? All the posted information is added to a global array that is called: $_POST. It’s a predefined constant. Although you can use it as you wish, it’s main use is for values coming from an HTML form. Now, the $_POST[] is for the newer versions of PHP. If you are using an older version ( PHP <= 4.3.1), then you would want to use $HTTP_POST_VARS[]. If we change the form method from “post” to “get”, we need to use $_GET[] and $HTTP_GET_VARS[] respectively. Using “get”, all the values are passed through the URL so anyone can see them.
So now we have the name and age. But what about the Chocolate button? It’s the same as all the others–you just refer to it using the name value. We named our button “Submit”, so we’ll get it using $_POST[‘Submit’]. Each form value must be referred to using $_POST[‘name of field’].

<?php

$name = $_POST[‘name’];
$age = $_POST[‘age’];
$chocolate = $_POST[‘Submit’];

echo “Hello “.$name.”!!  You are “.$age.” year(s) old.<br><br>
    Did you know: “.$chocolate.” too!!!”;

?>

Using the following inputs:
Name: Brett
Age: 21
Button Pressed: “I Love Chocolate”
It will output:
Hello Brett!! You are 21 year(s) old. Did you know: I Love Chocolate too!!
It’s that easy. You can make your forms as intricate and in-depth as you want. I haven’t seen people ask too many questions about radio buttons, checkboxes, and lists, so I guess it’s not that difficult to grasp. If I see requests for it, I’ll revisit this topic.

1
|
2
|
3
|
4
|
5