PHP: More Forms and Scripts

Derek Bridge

Department of Computer Science,
University College Cork

PHP: More Forms and Scripts

Aims:

langform.html: an (X)HTML form with checkboxes

<form action="langscript.php" method="get">
  <p>
   Which of these do you know?
  </p>
  <p>
   <input type="checkbox" name="langs[]" value="Groovy" id="groovyBox" />
   <label for="groovyBox">Groovy</label>
   <input type="checkbox" name="langs[]" value="Java" id="javaBox" />
   <label for="javaBox">Java</label>
   <input type="checkbox" name="langs[]" value="PHP" id="phpBox" />
   <label for="phpBox">PHP</label>
  </p>
  <p>
   <input type="submit" value="Submit" />;
  </p>
</form>

Groups of checkboxes

langscript.php

<?php
  if ( ! isset($_GET['langs']) ) 
  {
     die('No languages! Are you stupid?');
  }
  $length = count($_GET['langs']);
  echo "You know the following {$length} languages:"; 
  echo '<ul>';
  foreach ($_GET['langs'] as $lang) 
  {
    echo "<li>$lang</li>";
  }
  echo '</ul>';
 ?>

Notes on langscript.php

Notes on langscript.php

Self-processing pages: example

Self-processing pages: observations

Sticky forms: example

  • A sticky form displays the values of the previous query
  • Here's some changes that don't seem too important...
<?php 
 $fahr = '';
 $output = '';
 if ( isset($_GET['submitted']) ) 
 {
    $fahr = $_GET['fahr'];
    $celsius = ($fahr - 32) * 5/9;
    $output = "{$fahr} Fahrenheit is {$celsius} Celsius";
 }
?>
  • But they allow one crucial change to the text-field in the form...
   <input type="text" name="fahr" id="fahrField"
             value="<?php echo $fahr; ?>" />

Sticky forms for user data validation

  • We often need to validate the user's data
    • e.g. to check something has been entered into a field
    • e.g. to check that what is entered is numeric
  • If there's an error, we display a message
    • Sticky forms are good for this because they can preserve what the user has already typed so s/he doesn't have to retype everything

Validation: example

<?php 
 $fahr = '';
 $output = '';
 if ( isset($_GET['submitted']) ) 
 {
    $fahr = $_GET['fahr'];
    if ( ! is_numeric($fahr) ) 
    {
       $output = "You must enter a numeric value";
    }
    else
    {	

       $celsius = ($fahr - 32) * 5/9;
       $output = "{$fahr} Fahrenheit is {$celsius} Celsius";
    }
 }
?>