我想在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
答案 0 :(得分:0)
更改此行
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
empty会将0视为空,但如果$ num1或$ num2未设置,则不会显示任何错误
答案 1 :(得分:0)
让我们使用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
}