我想在 PHP 中的用户数据中添加减法和其他函数。首先,我想检查字段是否为空。当我使用函数检查空时empty()
并提交零,然后它显示必需,这意味着它是空的。如何输入零并用我的第二个值加减?谢谢。我的代码在这里
<html>
<head>
</head>
<body>
<?php
if ($_SERVER['REQUEST_METHOD']=='POST'){
$num1=$_POST['num1'];
$num2=$_POST['num2'];
if (empty($num1 AND $num2)){
echo "Required";
}else{
if ($_POST['submit']=='Add'){
$num1=$_POST['num1'];
$num2=$_POST['num2'];
$add=$num1+$num2;
echo $add;
}
elseif ($_POST['submit']=='Subtract'){
$subtract=$num1-$num2;
echo $subtract;
}
elseif ($_POST['submit']=='Multiplication'){
$multiply=$num1*$num2;
echo $multiply;
}
elseif ($_POST['submit']=='Division'){
$division=$num1/$num2;
echo $division;
}
}
}
?>
<form action="" method="post">
<input type="number" name="num1">
<input type="number" name="num2">
<input type="submit" name="submit" value="Add">
<input type="submit" name="submit" value="Subtract">
<input type="submit" name="submit" value="Multiplication">
<input type="submit" name="submit" value="Division">
</form>
</body>
</html
让我们使用 v Sugumar 的答案,让它变得更容易:
function emp($value){
if (isset($value) && $value>=0 )
return true;//has value
else
return false;//empty
}
现在你只需要使用它:
if(emp($num1) and emp($num2)){
//You typed a value, do something
}
更改此行
if (empty($num1 AND $num2)){}
自
if (isset($num1) && isset($num2) && $num1>=0 && $num2>=0){}// this will show warning if $num1 or $num2 is not set
或
if (!empty($num1) && !empty($num2) && $num1>=0 && $num2>=0){}// this will not show warnings
空会将 0 视为空,但如果尚未设置 $num 1 或 $num 2,则不会显示任何错误