我的 php 表单中的输入字段出现问题。看起来像:
<input type="number" name="tmax" max="99" min="-99" placeholder="Temperatura max.">
Run Code Online (Sandbox Code Playgroud)
我想检查该字段是否为空。但问题是 php 认为0是空的。
if (empty($_POST['tmax'])) {
$tmax = null;
}else {
$tmax = $_POST['tmax'];
}
Run Code Online (Sandbox Code Playgroud)
如果用户将输入字段留空,则该值将被视为“null”,这是完美的。但如果用户写入0,这在表单中是可能的,它也会被视为空。
我还在 SQL 中将默认值设置为 null,但问题是,如果输入为空,程序会插入0表中。
解决方案:
这个解决方案对我来说效果很好:
if ($_POST['tmax'] == "") {
$tmax = null;
}else {
$tmax = $_POST['tmax'];
}
Run Code Online (Sandbox Code Playgroud)
并且还与is_numeric()
if (is_numeric($_POST['tmax'])) {
$tmax = $_POST['tmax'];
}else {
$tmax = 'null';
}
Run Code Online (Sandbox Code Playgroud)