INTRODUCTION
LESSONS
MORE PHP
|
03 - Arithmetic Using PHP
0 + 0 = 0
Homework: Upgrade
the calculator example to multiply and divide. Make sure it traps
the divide by zero error.
<!-- Here is the page source code for 03arithmetic.php -->
<?php
include "code.php"; // Contains the function used to display
// the source code of web pages.
// WHEN THE PAGE IS FIRST LOADED, THE $_POST ARRAY HAS NOT BEEN SET
// THESE THREE LINES DEAL WITH THIS CONDITION
if (isset($_POST[n1])) { $n1 = $_POST[n1]; } else { $n1 = 0; }
if (isset($_POST[n2])) { $n2 = $_POST[n2]; } else { $n2 = 0; }
if (isset($_POST[radiobutton])) { $rb = $_POST[radiobutton]; } else { $rb = ""; }
// IF BLANK DATA IS SUBMITTED, IT IS REPLACED BY SENSIBLE DEFAULT VALUES
if ((! isset($n1)) or ($n1 == "")) { $n1 = 0; }
if ((! isset($n2)) or ($n2 == "")) { $n2 = 0; }
if ((! isset($rb)) or ($rb == "")) { $rb = "add"; }
// CHECK FOR NUMERIC INPUT AND THE VALUE IN $rb
if ((is_numeric($n1)) and (is_numeric($n2)) and ($rb == 'add'))
{
$answer = $n1 + $n2;
$output = "<h3>$n1 + $n2 = $answer</h3>\n";
}
else
if ((is_numeric($n1)) and (is_numeric($n2)) and ($rb == 'subtract'))
{
$answer = $n1 - $n2;
$output = "<h3>$n1 - $n2 = $answer</h3>\n";
}
else
{
$output = "<h3>Input Error</h3>";
}
?>
<html>
<head>
<title>Arithmetic Using PHP</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<table border="1" cellpadding="4" cellspacing="0">
<tr valign="top">
<td><?php include "nav.php"; ?></td>
<td>
<h1>03 - Arithmetic Using PHP</h1>
<form name="form1" method="post" action="03arithmetic.php">
<table border="1" cellspacing="0" cellpadding="4">
<tr>
<td><div align="right">First Number</div></td>
<td><input name="n1" type="text" id="n1" value="<?php echo "$n1"; ?>"></td>
</tr>
<tr>
<td><div align="right">Second Number</div></td>
<td><input name="n2" type="text" id="n2" value="<?php echo "$n2"; ?>"></td>
</tr>
<tr>
<td colspan="2">
<div align="center">
Add <input name="radiobutton" type="radio" value="add" checked>
Subtract <input type="radio" name="radiobutton" value="subtract">
</div>
</td>
</tr>
<tr>
<td colspan="2">
<div align="right">
<input type="submit" name="Submit" value="Submit">
</div>
</td>
</tr>
</table>
</form>
<?php echo "$output\n"; ?>
<p><strong><font color="#FF0000">Homework:</font></strong> Upgrade
the calculator example to multiply and divide. Make sure it traps
the divide by zero error.</p>
<?php dump_page("03arithmetic.php"); ?>
</td>
</tr>
</table>
</body>
</html>
|
|