In my form, a team's score is input, validated by the PHP script and then passed to the MySQL database. However, I want to make sure that a positive integer is being submitted, so there are no problems on the back-end when league standings are tabulated.
Research led me to the conclusion that using is_numeric would be the best way to go about this. However, it fails to recognize zero as an integer and that presents a problem for me. When I echo it in an array by itself, it shows as true, but something about the way I've written it in the script is not working.
I tried converting the $_POST with intval first and then processing the number with is_numeric, but that doesn't seem to help. Here's the code:
// Validate the away score:
if (empty($_POST['away_score'])) {
echo "You forgot to enter the away score.<br>";
$validate = 'false';
} elseif (!is_numeric($_POST['away_score'])) {
echo "You entered an invalid score for the away team.<br>";
$validate = 'false';
} else {
$away_score_value = mysqli_real_escape_string($db, trim($_POST['away_score']));
$validate = 'true';
}
Any thoughts?
The string
'0'
is not truthy. That means that anything that checks it in a boolean'ish manner will treat it as false. In particular,empty($_POST['away_score'])
will evaluate totrue
, sois_numeric
would never even get a chance to fail.Short version:
empty
is too wishy-washy in this case. Check for null and''
explicitly.