I am kind of new to PHP but I was having an issue. I have a PHP form that I submit. The assignment instructs that I must use a filter_input to check if the values are null. However, when i use the if/else statements it keeps stopping on the 2nd NULL option even if I input words. I check using var_dump and the variable is false. Why is the False message not coming up?
$product_name = filter_input(INPUT_POST, 'product_name');
$quantity = filter_input(INPUT_POST, 'quantity',FILTER_VALIDATE_INT);
$unit_price = filter_input(INPUT_POST, 'unit_price',FILTER_VALIDATE_INT);
var_dump($quantity);
//validate product_name
if ( $product_name == NULL) {
$error_message = 'Please enter a valid product name';
//validate quantity
} else if ( $quantity == NULL) {
$error_message = 'Quantity is null';
} else if ( $quantity == FALSE ) {
$error_message = 'Quantity must be a valid number.';
} else if ( $quantity <= 0 ) {
$error_message = 'Quantity must be greater than zero.';
//unit_price
} else if ( $unit_price == NULL ) {
$error_message = 'Unit Price is null';
} else if ( $unit_price <= 0 ) {
$error_message = 'Unit Price must be greater than zero.';
// set error message to empty string if no invalid entries
} else {
$error_message = '';
}
// if an error message exists, go to the purchase2.php page
if ($error_message != '') {
include('purchase2.php');
exit();
}
I expected that the FALSE message would come up but it keeps stopping at NULL and saying Quantity is null.
By default,
filter_inputwill returnnullif the key is not set orfalseif the filter fails. Unless someone has manipulated the form code before submitting it or you forgot/misnamed one of the inputs, those keys will always be present, so none of the filters should ever return null.But since
nullis a falsey value, you can evaluate both possibilities the same way and it doesn't really matter which one it was.If that key is missing from $_POST for some reason and
filter_inputreturnsnull, then they didn't enter a valid value, and if it's not missing from $_POST but it's invalid andfilter_inputreturnsfalse, then they didn't enter a valid value. Either way they should get the same message.