Page 1 of 1

code not giving the expected output...

Posted: Sun Nov 06, 2011 12:46 pm
by steven11
Hello Everyone, I am trying to run this simple code but it is giving me some absurd output. Details are here:

OS: Windows 7 home premium
PHP version: 5.3.8
Web server: IIS on windows 7

****************************************************************************
HTML file (calculate_form.html):

Code: Select all

<html>
<head>
<title>Calculation Form</title>
</head>
<body>
<form method="post" action="calculate.php">
<p>Value 1: <input type="text" name="val1" size="10"></p>
<p>Value 2: <input type="text" name="val2" size="10"></p>
<p>Calculation:<br>
<input type="radio" name="calc" value="add"> add<br>
<input type="radio" name="calc" value="subtract"> subtract<br>
<input type="radio" name="calc" value="multiply"> multiply<br>
<input type="radio" name="calc" value="divide"> divide</p>
<p><input type="submit" name="submit" value="Calculate"></p>
</body>
</html>
*********************************************************************************

PHP file (calculate.php):

Code: Select all

<?php
if (($_POST[val1] == "") || ($_POST[val2] == "") || ($_POST[calc] =="")) {
header("Location: calculate_form.html");
exit;
}
if ($_POST[calc] == "add") {
$result = $_POST[val1] + $_POST[val2];
} else if ($_POST[calc] == "subtract") {
$result = $_POST[val1] - $_POST[val2];
} else if ($_POST[calc] == "multiply") {
$result = $_POST[val1] * $_POST[val2];
} else if ($_POST[calc] == "divide") {
$result = $_POST[val1] / $_POST[val2];
}
echo <title>Calculation Result</title>;
echo <br>The result of the calculation is: $result;
echo <p><a href=\calculate_forum.html\ target=\_self\> Another</a>;
?>
**********************************************************************************

The output i am getting on the browser is:

Calculation Result; echo
The result of the calculation is: $result; echo
Another; ?>

Re: code not giving the expected output...

Posted: Sun Nov 06, 2011 1:24 pm
by mikeashfield
You're not escaping the HTML in your code. Try this code and come back with the errors it produces (if any) :)

Code: Select all

<?php
if (($_POST[val1] == "") || ($_POST[val2] == "") || ($_POST[calc] =="")) {
header("Location: calculate_form.html");
exit;
}
if ($_POST[calc] == "add") {
$result = $_POST[val1] + $_POST[val2];
} else if ($_POST[calc] == "subtract") {
$result = $_POST[val1] - $_POST[val2];
} else if ($_POST[calc] == "multiply") {
$result = $_POST[val1] * $_POST[val2];
} else {
$result = $_POST[val1] / $_POST[val2];
}
?>
<title>Calculation Result</title>
<br>The result of the calculation is: <?php echo $result; ?>
<p><a href=\calculate_forum.html\ target=\_self\>Another</a>

Re: code not giving the expected output...

Posted: Sun Nov 06, 2011 9:01 pm
by steven11
thank you for your help!!
works fine now :)

Re: code not giving the expected output...

Posted: Mon Nov 07, 2011 10:52 am
by mikeashfield
No Problem, HTH.