我有一个html表单,可以从用户那里获取用于计算的数字。给出了第一个数字。第二个由用户输入。结果将发布到同一页面。但是得到的答案现在是第一个数字,并且再次由用户输入第二个数字。第一个代码适用于第一次计算。但是下一个仍然使用给定的数字,而不是结果。我认为我应该使用if/else来测试是否输入了提交。但第一个答案不会在下一轮中传递,$first=$total(我得到了未定义的变量total(。
没有其他声明:
<head>
<title>Calculate</title>
</head>
<body>
<?php
$first = 2;
if(isset($_POST['Calculate']))
{
$second = (!empty($_POST['second']) ? $_POST['second'] : null);
$total = $first+$second;
print "<h2>Results</h2>";
print "The total of the two numbers: $first + $second = $total <p>";
$first=$total;
}
?>
<h2>Calculate</h2>
<p><?php echo "First Number: $first"; ?></p>
<br>
<form action = "index.php" method = "POST">
Second Number: <input type = "text" name = "second"><br>
<input type = "submit" name = "Calculate"/>
</form>
</body>
</html>
使用else语句:
<head>
<title>Calculate</title>
</head>
<body>
<?php
if(isset($_POST['Calculate']))
{
$first=$total;
$second = (!empty($_POST['second']) ? $_POST['second'] : null);
$total = $first+$second;
print "<h2>Results</h2>";
print "The total of the two numbers: $first + $second = $total <p>";
}
else {
$first = 2;
$second = (!empty($_POST['second']) ? $_POST['second'] : null);
$total = $first+$second;
}
?>
<h2>Calculate</h2>
<p><?php echo "First Number: $first"; ?></p>
<br>
<form action = "index.php" method = "POST">
Second Number: <input type = "text" name = "second"><br>
<input type = "submit" name = "Calculate"/>
</form>
</body>
</html>
我把表格改成
<form action = "index.php" method = "POST">
<input type="hidden" name="first" value="$first" />
Second Number: <input type = "text" name = "second"><br>
<input type = "submit" name = "Calculate"/>
</form>
</body>
</html>
但得到了同样的结果。
您从不麻烦传递这两个值,只需显示结果,然后提示输入新值。您需要将"上一个"值嵌入为隐藏的表单字段:
<form ...>
<input type="hidden" name="first" value="$first" />
<input type="text" name="second" />
首先,如果条件中的$second
和$total
的值相同,则不需要在条件中设置它们的值。第二,将三元赋值封装在括号中,以便将值设置为布尔值,而不是$_POST
数组的值。所以你有:
$second = (!empty($_POST['second']) ? $_POST['second'] : null);
应该在什么时候:
$second = !empty($_POST['second']) ? $_POST['second'] : null;
这里有一个更干净的方法:
$first = isset($_POST['Calculate']) ? $total : 2;
$second = !empty($_POST['second']) ? $_POST['second'] : 0;
$total = $first + $second;
if(isset($_POST['Calculate']))
{
print "<h2>Results</h2>";
print "The total of the two numbers: $first + $second = $total <p>";
}