Another User Defined Function

 

Introduction.  Now that you have seen one user defined function we will present another that converts temperature in degrees Fahrenheit to Celsius.

We are also going to experiment with making the form page the same ass the processing script page.  This is something we will get much involved with in future web pages.

The form page for this will be simpler than the last example.  You should call it user_convert_fahrenheit.php.

 

<?php
function convertToCelsius($local_input)
{
// obtaining the information from the form and comverting it
$txt_celsius = 5.0 * ($local_input - 32.0) / 9.0;
printf("%01.2f",$txt_celsius);
}
?>
<html>
<head>
<title>Echoing and Computing with the Inputted Information</title>
</head>

<body bgcolor=000056 text=cccccc>
<form action="user_convert_fahrenheit_return.php" method = post>
<table align = center>
<tr>
<td><font size = 4 color=cccccc>Please Enter Degree Fahrenheit: </font>
</td>
<td><input type=text name="txt_fahrenheit" size=6 value = <?php if ($txt_fahrenheit != "")
printf("%01.2f",$txt_fahrenheit); ?>>
</td>
</tr>
<tr>
<td colspan = 2 align = center><input type = submit name="submit" value="convert">
</td>
</tr>
<tr>
<td><font size = 4 color=cccccc>Degrees Celsius: </font>
</td>
<td><input type=text name="txt_celsius" size=6 value = <?php if ($txt_fahrenheit != "")
convertToCelsius($txt_fahrenheit); ?> >
</td>
</tr>
</table>
</form>

</body>
</html>

 

You should notice these two major things about the code.

  • the action in the <form> tag points to the file itself which contains the form
  • some PHP is nestled into the value in the two textboxes so that the results of the inputs and computations will be displayed within them

Now we will modify the code so it will not write to the text box within the function.  This PHP will return the value so that the write is done later.  You should call this user_convert_fahrenheit_return.php.

 

<?php
function convertToCelsius($local_input)
{
// obtaining the information from the form and comverting it
$local_celsius = 5.0 * ($local_input - 32.0) / 9.0;
return $local_celsius;
}
?>
<html>
<head>
<title>Echoing and Computing with the Inputted Information</title>
</head>

<body bgcolor=000056 text=cccccc>
<form action="user_convert_fahrenheit_return.php" method = post>
<table align = center>
<tr>
<td><font size = 4 color=cccccc>Please Enter Degree Fahrenheit: </font>
</td>
<td><input type=text name="txt_fahrenheit" size=6 value = <?php if ($txt_fahrenheit != "")
printf("%01.2f",$txt_fahrenheit); ?>>
</td>
</tr>
<tr>
<td colspan = 2 align = center><input type = submit name="submit" value="convert">
</td>
</tr>
<tr>
<td><font size = 4 color=cccccc>Degrees Celsius: </font>
</td>
<td><input type=text name="txt_celsius" size=6 value = <?php if ($txt_fahrenheit != "")
$txt_celsius = convertToCelsius($txt_fahrenheit);
printf("%01.2f",$txt_celsius);?> >
</td>
</tr>
</table>
</form>

</body>
</html>