How do I process the information from a form

In particular how do I 'extract' the information from submitted elements like a text box, radio button, check-box, listbox etc?

Check out the full source code

Creating the webform

First we must create a web-form. The following code creates a form for a room service menu. The user can enter a room-number into the input field, select their gender from a group of radio buttons, tick the type(s) of breakfast they would like from a group of check boxes and select the size of the serving from a listbox.

<form name="Form1" action="<php echo $_SERVER['PHP_SELF']; ?>" method="POST" >
<p>Room Number<br />
<input type="text" name="roomnumber" maxlength="60" size="60" /></p>
 
<p>Gender<br />
<input type="radio" name="gender" value="M" />Male  
<input type="radio" name="gender" value="F" />Female  
<input type="radio" name="gender" value="N" />Not Sure</p>
 
<p>Select type of breakfast you want<br />
<input type="checkbox" name="Cereal" />Cereal  
<input type="checkbox" name="Toast" />Toast  
<input type="checkbox" name="Bacon and Eggs" />Bacon and Eggs</p>
 
<p>Select the Size of the Breakfast<br />
<select name="breakfastSize" size="1">
  <option value="" selected>Please Select</option>
  <option value="3">King Size</option>
  <option value="2">Normal Size</option>
  <option value="1">Small Size</option>
</select></p>
 
<p><input type="submit" name="submit" value="submit" /></p>
</form>

The action property has been set to $_SERVER['PHP_SELF'], and the method to POST. This means that when the submit button is pressed, the information from the web-form is sent to the page where the web-form resides on.

An alternative could have been to physically name the webpage in the action property, however by using $_SERVER['PHP_SELF'] we can be assured that the information is always submitted to the current page, no matter what the page name is or how many times you change it.


Processing the submit Button

Before we can process any of the information submitted, we need to first ascertain if the submit button has been pressed. If it has been pressed then we'll display a thank-you note, otherwise we'll display the form. Once we have that part done, we can then move onto processing the individual controls.

To determine if the submit button has been pressed, use the isset function.

<html>
<head></head>
<body>
<?php
if(isset($_POST['submit']))		//submit button pressed
  {
  echo '<p>Thank-you.  Breakfast will be ready soon!</p>'
 
  //Process the individual form controls
  }
else			//display the form
  {
  ?>
 
<!- HTML code for the form -->
 
<?php
   }	//close off the ending bracket for the else statement
?>
 
</body>
</html>

Additional Notes
Because the form was submitted via POST, we must use the $_POST array to access the information. Had the data been set via GET, (url parameters) then we would have used $_GET to access the submitted information.


Processing the text input

Our first example will be to display the value from the text input onto the browser. There are two techniques that can be used, and the choice between them comes down to user preference (or ease of programming).

Technique One - echo with single quotes

 echo '<p>Breakfast will be delivered to room ' . $_POST['roomnumber'] . '</p>';

Technique Two - echo with double quotes

 echo "<p>Breakfast will be delivered to room {$_POST['roomnumber']}</p>";

Regardless of the technique used, if the user doesn't enter a room number the message that is displayed will be 'Breakfast will be delivered to room'. What would be more appropriate is a message like 'Breakfast will be available from the dining room'. This can be accomplished like so.

Checking to see if the field has a value

if(empty($_POST['roomnumber']))		//text-input is empty!
  echo '<p>Breakfast will be available from the dining room</p>';
else
  echo "<p>Breakfast will be delivered to room {$_POST['roomnumber']}</p>";

Processing the radio buttons

In this example the type of salutation sent to the browser will be determined by the type of gender selected. I.E. if the radio button for male was selected then we'll say good morning Mr. If the radio button for female was selected then we'll say good morning Miss. If no radio button is selected, then we'll just say good morning.

switch($_POST['gender'])			//gender is the name of the radio button
  {						//group used in the HTML form.
  case 'M':				        //radio button value for Male
    echo '<p>Good Morning Mr</p>';
  break;
 
  case 'F':			                //radio button value for Female
    echo '<p>Good Morning Miss</p>';
  break;
 
  case 'N':	                                //radio button value for Not Sure.
                                                //Let this fall through to the default.
  default:
    echo '<p>Good Morning</p>';
  break;
  }

Additional Notes
The HTML for displaying the radio buttons is shown below.

<input type="radio" name="gender" value="M" />Male  
<input type="radio" name="gender" value="F" />Female  
<input type="radio" name="gender" value="N" />Not Sure

The radio buttons are grouped together by name which is how the browser is able to make them mutually exclusive (which means that only one radio button in the group can be checked at any time). The value is also passed in the $_POST array, with the name as the key/index. If multiple selections are necessary, then you would either create additional groups or use a different control (e.g. checkbox).

In this example we used a switch statement with the radio button to assess which button had been selected. The result then determines the type of message to display on the browser.


Processing the checkboxes

In this example we will use string concatenation to build a sentence based on the check boxes ticked so that the output might be something like 'You are having Cereal, Toast.' if the Cereal and Toast check boxes were ticked.

$sentence = 'You are having ';	//create first part of sentence
$s_end = FALSE;			//set the end variable to false
 
if(isset($_POST['Toast']))		//concatenate 'Toast' to the sentence if the
  $sentence .= 'Toast, ';		//toast checkbox has been ticked
 
if(isset($_POST['Cereal']))		//concatenate 'Cereal' to the sentence if the
  $sentence .= 'Cereal, ';		//cereal checkbox has been ticked
 
if(isset($_POST['Bacon_Eggs']))	//concatenate 'Bacon and Eggs' to the sentence
  {					//if the Bacon_Eggs checkbox has been ticked.
  $s_end = TRUE;			//Also set the $s_end variable to true, so we
  $sentence .= 'Bacon and Eggs';	//know not to amend the sentence later
  }
 
//if $s_end is not true, then our sentence may end with a comma and space.
//Remove the last two characters from the sentence.
if(!$s_end)
  $sentence = substr($sentence, 0, strlen($sentence) - 2);
 
//if no checkboxes had been selected, then $s_end would be false and the last two
//characters removed from the sentence.  Only display the sentence if at least one
//checkbox has been ticked.
if($sentence <> 'You are havin')
  echo '<p>' . $sentence . '.</p>';

In this example we have not made use of the value attribute of the check box control. In fact we didn't even specify the value attribute in the HTML form. All we were interested in was whether or not the check box had been selected. That is done by using the isset function and passing it the name of the control.


Processing the listbox

In this example we'll check to see if anything has been selected, and if it has we'll display an appropriate message. This time however, because the option values for the list box are numeric and in sequential order, we'll store the messages in an array.

$breaky_array = array(1 => 'Small Size', 'Normal Size', 'King Size');
  if(isset($_POST['breakfastSize']) && !empty($_POST['breakfastSize']))
    echo '<p>You are having a ' .
             $breaky_array[$_POST['breakfastSize']] .
             ' breakfast</p>';

If you compare the breaky_array with the option values of the list box you'll notice that the array data matches that of the listbox. I.E. option Small Size has a value of 1, Normal Size has a value of 2 and so on. So in our code all we need to do is pass the value of the selected item that was posted from the listbox (remember it is the value that is posted by the form) to the breaky_array to get the corresponding label.

As an example, if we selected 'King Size' then the form would post the value 3 for the breakfastSize listbox. The value 3 would be contained in the $_POST['breakfastSize'] superglobal and we use that value to choose the appropriate array value to construct our sentence with.

Tags: 

Comments

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.