Physics & Computer Science > CP363 : Home > Implementation Information
Version: 2020-02-06 11:02

CP363 : Other Form Inputs

The examples on this page assumes the use of the class and connection defined at the top of the Selecting Data page.


Radio Buttons

The following HTML code:

  <p>Gender:<br />
    <input name="gender" type="radio" value="M">Male<br />
    <input name="gender" type="radio" value="F">Female
  </p>

produces this widget:

Gender:
Male
Female

Note that both input elements have the same name. Because of this only one of the two buttons can be pushed. The value attribute assigns a value to each selection. Thus the variable $_POST['gender'] will be submitted with one and only once of the values M or F.


Check Boxes

The following HTML code:

  <p>Toppings:
  <input name="topping[]" type="checkbox" value="Mustard">Mustard
  <input name="topping[]" type="checkbox" value="Ketchup">Ketchup
  <input name="topping[]" type="checkbox" value="Onions">Onions
  <input name="topping[]" type="checkbox" value="Relish">Relish
  </p>

produces this widget:

Toppings: Mustard Ketchup Onions Relish

Note this use of the square brackets [] at the end of the input field name topping. This causes PHP to treat the returned values of these checkboxes as an array. Otherwise only one of the checked values is returned. Thus, if a user checks the boxes for Mustard, Onions, and Relish, the value of $_POST['topping'] is an array with three numbered elements:

Array
(
    [0] => Mustard
    [1] => Onions
    [2] => Relish
)

If none of the boxes are checked then the variable $_POST['topping'] does not exist at all. You can check for the existence of a variable with the isset method, as in this example:

if( isset( $_POST['topping'] ) ) {
    ...

Note that the use of square brackets in a form element name does not pass certain types of X/HTML validation.