【问题标题】:functions and validating values函数和验证值
【发布时间】:2020-03-12 16:26:32
【问题描述】:

我正在努力让PHP 验证值中的负值、数字和非数字以及空值。

如果值为负、空、非数字,我需要 php 显示错误消息。

我还遇到了一个问题,即无法从$_POST 中的HTML 表单中获取值。

$first = $_POST['first'];
$second = $_POST['second'];
$operation = $_POST['operation'];

在我的表单中,每个值的名称都正确拼写为我拥有的负值

if ($first || $second < 0) {
    print("<h2> Error one or more inputs are not negative numbers</h2>");
     echo("<a href="calculator.html"></a>");
}

对于我有的空数字:

if (empty($first) || empty($second) == true) {
    print("<p> One or more input field is empty </p>");
    echo("<a href="calculator.html"></a>");
}

对于非数字值:

if (!is_numeric($first) || !is_numeric($second) == false) {
    print("<h2> Error one or more inputs are not numbers</h2>");
    echo("<a href="calculator.html"></a>");
}

我的问题是,每次输入任何数字时,如果是 truefalse,我都会收到错误消息。

【问题讨论】:

  • “我的问题是,每次输入任何数字时,我都会收到错误消息,无论是真是假” - 究竟是什么?
  • if ($first or $second &lt; 0)
  • 您的!is_numeric ... == false 是双重否定的。你为什么用那个?
  • 您需要将条件应用于您正在测试的每个值,例如if ($first &lt; 0 || $second &lt; 0) 并且您不需要比较布尔值,因此只需编写 if (empty($first) || empty($second))if (!is_numeric($first) || !is_numeric($second))。注意 PHP 中的逻辑或运算符是 ||
  • nick 我使用的是 or 运算符来查看其中是否有人为空或负数或字符串

标签: php function if-statement include


【解决方案1】:

首先,更改此条件,因为 PHP 会将其理解为 ($first || $second) &lt;0,其中 $first || $second 将被评估为单个布尔语句,然后返回的布尔值将被强制转换为 int (true -> 1, false -> 0) 然后用&lt;0检查,总是假的,所以代码应该改成:

if ($first<0 or $second < 0)
{
   print("<h2> Error one or more inputs are not negative numbers</h2>");
   echo("<a href="calculator.html"></a>");
}

在这个块中,== true 是无用的,因为 php 中的if this or that 意味着“检查第一个值并查看是否正确转换为布尔值,是真还是假,然后在这之间应用 or两个值”,在这种情况下,“this”和“that”已经是布尔值,所以它完全没用,但如果你想明确它,代码应该看起来像empty($first) == true or empty($second) == true否则你只明确两者之一,或者最好把它拿出来,所以代码应该看起来像

if (empty($first) or empty($second))
{
   print("<p> One or more input field is empty </p>");
   echo("<a href="calculator.html"></a>");
}

而在最后一段代码中,逻辑是错误的,因为你要检查两个值中的一个是否不是数字,所以!is_numeric($value)如果不是数字则返回true,如果是则返回false数字,因此代码应更改为

if (!is_numeric($first) or !is_numeric($second))
{
 print("<h2> Error one or more inputs are not numbers</h2>");
 echo("<a href="calculator.html"></a>");
}

另外,在我看来,我建议您使用 || 而不是 or 。和&amp;&amp; 而不是and,因为大多数其他语言都使用该运算符,所以一旦你学会了所有语言,你就可以了

关于无法从请求中获取数据,请在表单中发布答案,我将使用可能的解决方案编辑此答案

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2015-12-30
  • 1970-01-01
  • 2020-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多