零在 PHP 中被视为空

Zero considered as empty in PHP

我的 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 中将默认值设置为空,但问题是,如果输入为空,程序会在 table.[=19 中插入 0 =]

解决方案:

这个解决方案对我来说很好用:

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

还有is_numeric()

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

正如您所说,0 被认为是空的。

你要的函数是set()。

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

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

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

感谢 Rafa 的重要说明

检查条件是否为空,并且不为零。零值是 "empty",因此通过添加这两个检查,您可以确保如果输入为空 和 [=33],变量 $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) 验证它以确保输入的内容实际上是一个数字。

你可以使用

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

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

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

如果您想要占位符 - 您可以使用此代码:

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

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

和php到:

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