Hairy Mike's Tutorials: PHP

Forms And PHP Pt.2

On the last page I showed you how to make an interface for someone else's script. Now it is time for you to make your own tool. For this example, we will make a form to convert miles to kilometers. The form is HTML: a text input, a submit button, and a text input for the results.

<style>
fieldset
 { 
 width:fit-content; margin:auto; text-align:center; 
 border:solid; border-color:red; border-radius: 10px;;
 }
legend { color:blue ;}
.wide { width:5em;}
</style>
<form>
<fieldset>
<legend>Kilometers To Miles</legend>
<input type="number" name="km" class="wide" step=".01" 
  value="" placeholder="XX.XX">
<input type="submit" name="" value="Convert">
<input type="" name="mi" class="wide" 
   value="" disabled>
</fieldset>
</form>
Kilometers To Miles

Notice that the first input is named "km" so it will be $_GET['km'] when submitted to a PHP script. You don't want your script executing if nothing has been submited so you can test with isset() to see if $_GET['km'] has been set and is_numeric() to make sure that it is a number. A quick check with Google and you find that one kilometer is 1.609344006 miles and a little arithmetic gives you the PHP to convert miles to kilometers. You can use round() to round the result:

<?php  $mi = round($km/1.609344006, 4); ?>

To generate an answer, echo it in the "miles" text box

<input type="" name="mi" class="wide" 
   value="<?php echo "$mi"; ?>" disabled>
Show example | Show code