使用先前计算结果的PHP表单计算

时间:2014-03-23 03:58:43

标签: php html forms if-statement form-submit

我有一个html表单来从用户那里获取一个数字进行计算。给出第一个数字。第二个是由用户输入的。结果发布到同一页面。但结果答案现在是第一个数字,用户又输入第二个数字。 第一个代码适用于第一次计算。但是下一个仍然使用给定的数字,而不是结果。我相信我应该使用if / else来测试是否输入了提交。但第一个答案是没有通过下一轮传递$ first = $ total(我得到未定义的变量总数)。

没有else语句:

 <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> 

但得到了相同的结果。

2 个答案:

答案 0 :(得分:1)

你永远不会费心传递这两个值,只显示结果然后提示输入新值。您需要将“previous”值嵌入为隐藏的表单字段:

<form ...>
   <input type="hidden" name="first" value="$first" />
   <input type="text" name="second" />

答案 1 :(得分:0)

首先,您不需要在条件内设置$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>"; 
}