1

我有这个表格,我试图用它来获取一些用户输入的变量并将它们传递给 calculate.php 以计算和显示结果。

计算.html

<HTML>
<HEAD>
<TITLE>Calculation Form</TITLE>
</HEAD>
<BODY>
<FORM METHOD="POST" ACTION="calculate.php">
<P>Value 1: <INPUT TYPE="text" NAME="vall" 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:

        <?
if (($_POST["vall"] == "") || ($_POST["val2"] == "") || ($_POST["calc"] =="")) {
    header("Location: http://localhost/calculate.html");
exit;
}

if ($_POST["calc"] == "add") {
   $result = $_POST["vall"] + $_POST["val2"];
} else if ($_POST["calc"] == "subtract") {
   $result = $_POST["vall"] - $_POST["val2"];
} else if ($_POST["calc"] == "multiply") {
   $result = $_POST["vall"] * $_POST["val2"];
} else if ($_POST["calc"] == "divide") {
   $result = $_POST["vall"] / $_POST["val2"];
}

?>

<HTML>
<HEAD>
<TITLE>Calculation Result</TITLE>
</HEAD>
<BODY>

<P>The result of the calculation is: <? echo $result; ?></P>

</BODY>
</HTML>

谁能说我的错误在哪里,因为我只得到: 计算的结果是:

4

4 回答 4

1

"您在所有的数组索引中都错过了s $_POST[],因此您需要添加"".

<?
if (($_POST["vall"] == "") || ($_POST["val2"] == "") || ($_POST["calc"] =="")) {
    header("Location: http://localhost/calculate.html");
exit;
}

if ($_POST["calc"] == "add") {
   $result = $ POST[vall] + $_POST[val2];

} else if ($_POST["calc"] == "subtract") {
   $result = $_POST["vall"] - $_POST["val2"];
} else if ($_POST["calc"] == "multiply") {
   $result = $_POST["vall"] * $_POST["val2"];
} else if ($_POST["calc"] == "divide") {
   $result = $_POST["vall"] / $_POST["val2"];
}

?>
于 2012-11-17T11:26:15.477 回答
1

这些$_POST[vall]需要$_POST['vall']。字符串文字vall是关键。

于 2012-11-17T11:27:18.767 回答
0

您在 calculate.php 的第 8 行有一个错误:

$result = $ POST[vall] + $_POST[val2];

应该:

$result = $_POST["vall"] + $_POST["val2"];

并考虑到以前的答案

于 2012-11-17T11:33:57.140 回答
0

可能只是在这里打错了,但是 - 除了其他人所说的之外,你忘了关闭</form>标签

<INPUT TYPE="radio" NAME="calc" VALUE="divide"> divide</P>

<P><INPUT TYPE="submit" NAME="submit" VALUE="Calculate"></P>

</FORM> <!-- MISSING -->

</BODY>

我还会在处理之前检查 POST 请求:

if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
   // do your stuff
}
于 2012-11-17T11:48:20.703 回答