在PHP

时间:2017-07-29 15:41:48

标签: php forms input is-empty

我的php表单中的输入字段出现问题。它看起来像:

<input type="number" name="tmax" max="99" min="-99" placeholder="Temperatura max."> 

我想检查字段是否为空。但问题是php认为0为空。

if (empty($_POST['tmax'])) {
  $tmax = null;
}else {
  $tmax = $_POST['tmax'];
}

如果用户将输入字段留空,则该值被视为“null”,这非常有效。但是,如果用户在表单中写入0,这也可能被视为空。

我还在SQL中将默认值设置为null,但问题是,如果输入为空,程序会在表中插入0

SOLUTION:

这个解决方案适用于我:

if ($_POST['tmax'] == "") {
  $tmax = null;
}else {
  $tmax = $_POST['tmax'];
}

还有is_numeric()

if (is_numeric($_POST['tmax'])) {
  $tmax = $_POST['tmax'];
}else {      
    $tmax = 'null';
}

6 个答案:

答案 0 :(得分:3)

检查条件是否为空,也不为零。零值为“空”,因此通过添加两个检查,如果输入为空不为零,则确保变量$tmax将设置为null

if (empty($_POST['tmax']) && $_POST['tmax'] != 0) {
    $tmax = null;
} else {
    $tmax = $_POST['tmax'];
}

这也将接受“foo”作为值,因此您应该检查或验证输入是有效数字(以及您指定的范围内)。您还可以实现is_numeric($_POST['tmax']),甚至更好地使用filter_var($_POST['tmax'], FILTER_VALIDATE_INT)对其进行验证,以确保输入的内容实际上是一个数字。

答案 1 :(得分:1)

此代码适用于您想要获得的内容。

if (!isset($_POST['tmax']) || $_POST['tmax'] == '') {
    $tmax = null;
}else {
    $tmax = $_POST['tmax'];
}

答案 2 :(得分:1)

如果你想拥有占位符 - 你可以使用这段代码:

<input type="number" name="tmax" max="99" min="-99" onclick="if (this.value == '') {this.value='0';} " placeholder="Temperatura max.">

不要忘记添加验证(在空文件上发送表单检查之前)

和php to:

$tmax = 0;
if (isset($_POST['tmax'])) {
  $tmax = $_POST['tmax'];
}

答案 3 :(得分:0)

正如您所述,0被视为空。

你想要的功能是isset()。

if (!isset($_POST['tmax'])) {
    $tmax = null;
} else {
    $tmax = $_POST['tmax'];
}

或者,删除not运算符并切换代码块。

答案 4 :(得分:0)

您可以使用!is_numeric()代替empty()

谢谢你这么重要的一点,拉法

答案 5 :(得分:0)

你可以使用

if ($_POST['tmax'] == "") {
  $tmax = null;
}else {
  $tmax = $_POST['tmax'];
}
相关问题