【问题标题】:validating if statments for user inputs验证用户输入的 if 语句
【发布时间】:2019-12-02 05:53:33
【问题描述】:

如果其中 2 个为真,则两个错误链接都会显示并且消息彼此重叠,如果输入为 0,如果验证空输入的语句也会显示 此外,如果输入不是数字但另一个输入是数字 php 仍然会计算,但只会返回你给它的任何数字加上顶部的错误代码我该如何解决?

第一个语句是验证是否有任何值是0,如果操作是除法给出错误

if ($first == 0)
{ if ($operation == "Division")
  print("<h1>ERROR</h1>
        <p class=\"message\">YOU CAN NOT DIVIDE BY ZERO</p>");
}


else if($second == 0)
{ if ($operation =="Division")
  print("<h1>ERROR</h1>
        <p class=\"message\"> YOU CAN NOT DIVIDE BY ZERO</P>");
}

if 语句用于验证输入是否为数字

if (!is_numeric($first) or !is_numeric($second))
{
print("<h1> Error one or more inputs are not numbers</h1>" . "<p class=\"backlink\"><a href=\"calculator.html\">Go Back</a></p>");


}

第三个 if 语句用于验证正数

else if($first < 0 or $second < 0)
{
 print("<h1> Error one of more of your numbers is a negative</h1>" . "<p class=\"backlink\"><a href=\"calculator.html\">Go Back</a></p>");

}

this if 语句验证空输入

   if (empty($first) or empty($second))
  {
 print("<p class=\"message\"> One or more input field is empty </p>" . "<p class=\"backlink\"><a href=\"calculator.html\">Go Back</a></p>");

}else{

【问题讨论】:

  • 你能解释一下你期望的结果和你遵循的程序吗?
  • 如果任何一个为真,它将显示一条错误消息。如果没有正确处理 $first $second 和 $operator

标签: php html if-statement


【解决方案1】:

@irvdtcc 看代码,我知道你需要检查多个条件并只有在所有条件都为真时才显示结果。

要检查的标准 1) $first 和 $second 是大于 0 的数字 2) $first 和 $second 输入不为空。

最好的方法是为每个标准使用标志,如下所示。

<?php
$fl_positive=0;
$fl_num=0;
$fl_empty=0;
$error_message="";

//check if number is empty -- empty is true of $first=0 or $first="". In either case //empty($first) will result in true.
if(empty($first) or empty($second)){
  $fl_empty=1;
  $error_emssage . = "First or Second number is empty or zero";
}
elsif($first<0) or ($second<0)) {
  $fl_positive=1;
  $error_message . = " First or Second number is Negative";
}

//Check all criteria in the same manner

if($fl_positive==1) or ($fl_num==0) or ($fl_empty=0)){
  echo $error_message;
}
?>

【讨论】:

  • 解析错误:语法错误,第 17 行的 C:\xampp\htdocs\calculator.php 中的意外 '=' 是我在文件第 17 行用之前的 if 语句替换它时得到的是 $error_message 。 = "第一个或第二个是负数";
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-02
  • 2020-11-28
  • 1970-01-01
  • 1970-01-01
  • 2016-11-09
相关资源
最近更新 更多