Reputation: 73
I've got a problem with an input field in my php form. It looks like:
<input type="number" name="tmax" max="99" min="-99" placeholder="Temperatura max.">
I want to check whether the field is empty or not. But the problem is php considers 0
as empty.
if (empty($_POST['tmax'])) {
$tmax = null;
}else {
$tmax = $_POST['tmax'];
}
If the user leaves the input field empty the value is considered as 'null', which works perfectly. But if the user writes 0
, which is a possibility in the form, it is also treated as empty.
I've also set the default as null in SQL but the problem is, if the input is empty, the program inserts 0
in the table.
SOLUTION:
This solution works fine for me:
if ($_POST['tmax'] == "") {
$tmax = null;
}else {
$tmax = $_POST['tmax'];
}
And also with is_numeric()
if (is_numeric($_POST['tmax'])) {
$tmax = $_POST['tmax'];
}else {
$tmax = 'null';
}
Upvotes: 5
Views: 7334
Reputation: 237
if you want to have placeholder - you can use this code:
<input type="number" name="tmax" max="99" min="-99" onclick="if (this.value == '') {this.value='0';} " placeholder="Temperatura max.">
don't forget add validation (before send form check on empty fileds )
and php to:
$tmax = 0;
if (isset($_POST['tmax'])) {
$tmax = $_POST['tmax'];
}
Upvotes: 1
Reputation: 165
You can use !is_numeric()
instead empty()
thanks for such a important note, Rafa
Upvotes: 2
Reputation: 26450
Check if the condition is empty, and also not zero. A zero-value is "empty", so by adding both checks, you ensure that the variable $tmax
will be set to null
if the input was empty and not zero.
if (empty($_POST['tmax']) && $_POST['tmax'] != 0) {
$tmax = null;
} else {
$tmax = $_POST['tmax'];
}
This will also accept "foo" as a value, so you should check or validate that the input is a valid number (and also in the ranges you specified). You can also implement is_numeric($_POST['tmax'])
, or even better, validate it with filter_var($_POST['tmax'], FILTER_VALIDATE_INT)
to ensure that whatever was input is actually a number.
empty()
is_numeric()
filter_var()
filter_var()
Upvotes: 4
Reputation: 355
This code should work for what are you trying to get.
if (!isset($_POST['tmax']) || $_POST['tmax'] == '') {
$tmax = null;
}else {
$tmax = $_POST['tmax'];
}
Upvotes: 1
Reputation: 43
you may use
if ($_POST['tmax'] == "") {
$tmax = null;
}else {
$tmax = $_POST['tmax'];
}
Upvotes: 0
Reputation: 211
As you state, 0 is considered empty.
The function you want is isset().
if (!isset($_POST['tmax'])) {
$tmax = null;
} else {
$tmax = $_POST['tmax'];
}
Alternatively, remove the not operator and switch the code blocks.
Upvotes: 1