大家好我正在做这个用户计算表格,由于某些原因,当我添加按钮0 + 0时它给了我这个错误提示:未定义变量:添加/ var / www / html / 1018 / 5356684c357e7ff13ae21450a17d877d / Test-YT /第44行的index.php
除此之外,它适用于所有其他数字,这是我的PHP代码
<html>
<body>
<style><?php include "style.css" ?></style>
<form action="index.php" method="POST">
<table border="1">
<td>
<p>insert value one: <input type="text" name="num1"> <br>
<p>insert value two: <input type="text" name="num2"> <br>
</td>
<td>
<input type="submit" name="add" value="Addition">
<input type="submit" name="sub" value="Subtraction">
<input type="submit" name="mult" value="Multiplication">
<input type="submit" name="div" value="Division">
<input type="submit" name="all" value="Display All">
</td>
</table>
</form>
<div id="answers">
<?php
if (isset($_POST['num1']) && ($_POST['num2'])){
$val1 = $_POST['num1'];
$val2 = $_POST['num2'];
$add = $val1+$val2;
$sub = $val1-$val2;
$mult = $val1*$val2;
$div = $val1/$val2;
}
if (isset($_POST['add'])){
echo $add;
}
else{
echo "zero";
}
if (isset($_POST['sub'])){
echo $sub;
}
if (isset($_POST['mult'])){
echo $mult;
}
if (isset($_POST['div'])){
echo $div;
}
if (isset($_POST['all'])){
echo $add . "<br>" . $sub . "<br>" . $mult . "<br>" . $div . "<br>";
}
?>
</div>
</body>
</html>
答案 0 :(得分:7)
if (isset($_POST['num1']) && ($_POST['num2'])){
如果$_POST['num2']
为0
,则此表达式计算为false
且变量$ add未初始化,也可作为其他变量。
修改强> 如下所示,您可能需要以下内容:
if (isset($_POST['num1']) && isset($_POST['num2'])) {
但是看起来你也试图阻止除零错误。作为更好的解决方案,您可以首先定义所有变量,并且仅在除法之前检查非零值。
$add = $sub = $mult = $div = 0;
if (isset($_POST['num1']) && isset($_POST['num2'])){
$val1 = $_POST['num1'];
$val2 = $_POST['num2'];
$add = $val1+$val2;
$sub = $val1-$val2;
$mult = $val1*$val2;
if ($val2) {
$div = $val1/$val2;
}
}
因此,即使未提交num1
和num2
,您也可以确保脚本不会死亡。