所以,我用PHP编写了一个计算器,它写了结果,并且计算器使用了多少时间。
我第一次收到错误,但是当我点击任何提交按钮时,程序运行正常。 首次出错时我该怎么办?
该计划:
<html>
<body>
<div>
<?php
$using_calculator = $_POST['using_calculator'];
if(isset($_POST['plus'])){
$x = $_POST['number_1'];
$y = $_POST['number_2'];
$z = $x+$y;
$using_calculator++;
}else if(isset($_POST['minus'])){
$x = $_POST['number_1'];
$y = $_POST['number_2'];
$z = $x-$y;
$using_calculator++;
}else if(isset($_POST['multiplication'])){
$x = $_POST['number_1'];
$y = $_POST['number_2'];
$z = $x*$y;
$using_calculator++;
}else if(isset($_POST['division'])){
$x = $_POST['number_1'];
$y = $_POST['number_2'];
$z = $x/$y;
$using_calculator++;
}
?>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST">
<p>
First number: <input type="number" name="number_1"><br/>
Second number: <input type="number" name="number_2"><br/><br/>
<input type = "submit" name="plus" value="Plus">
<input type = "submit" name="minus" value="Minus">
<input type = "submit" name="multiplication" value="Multiplicate">
<input type = "submit" name="division" value="Divide">
<input type = "hidden" name="using_calculator" value="<?php echo $using_calculator; ?>">
</p>
</form>
<br>Result: <?php echo $z; ?>
<br>The calculator was used <?php echo $using_calculator; ?> times
</div>
</body>
我必须使用隐藏的输入字段,但我可以使用函数和对象。那么最好的方法是什么?
答案 0 :(得分:-1)
因为第一次变量(在你的php代码中)不是isset。所以它会显示错误。例如
$using_calculator = $_POST['using_calculator']; // first time $_POST['using_calculator'] is not isset
所以php会在第一时间输出错误信息。提交后,这些变量从POST初始化。因此,要避免此问题,请修改php代码,如下所示
<?php if(isset($_POST['using_calculator'])) { $using_calculator = $_POST['using_calculator']; if(isset($_POST['plus'])){ $x = $_POST['number_1']; $y = $_POST['number_2']; $z = $x+$y; $using_calculator++; }else if(isset($_POST['minus'])){ $x = $_POST['number_1']; $y = $_POST['number_2']; $z = $x-$y; $using_calculator++; }else if(isset($_POST['multiplication'])){ $x = $_POST['number_1']; $y = $_POST['number_2']; $z = $x*$y; $using_calculator++; }else if(isset($_POST['division'])){ $x = $_POST['number_1']; $y = $_POST['number_2']; $z = $x/$y; $using_calculator++; } } ?>