php - 零在PHP中被视为空

标签 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

解:

此解决方案对我来说很好:

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


还有is_numeric()

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

最佳答案

你可以用

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

关于php - 零在PHP中被视为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45391071/

相关文章:

PHP Mysql查询多项

php - 通过 PHP 将文件名上传到 SQL

php - 无法执行简单的 Hello World PHP 扩展

用于表单问候语的javascript

java - 它不要求输入,直接通过

javascript - 如何获得此表单验证代码的正确输出?

javascript - 如何在不使用表单的情况下从 JavaScript 向服务器提交 get 请求

javascript - 使用 JavaScript 提醒从输入中获取的 object() 值

javascript - 当用户选择文件时执行 javascript 函数

javascript - ° 添加 .placeholder 时不显示在占位符中