Zero considered as empty in PHP - php

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';
}

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.
PHP.net on empty()
PHP.net on is_numeric()
PHP.net on filter_var()
PHP.net on flags for usage in filter_var()

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.

This code should work for what are you trying to get.
if (!isset($_POST['tmax']) || $_POST['tmax'] == '') {
$tmax = null;
}else {
$tmax = $_POST['tmax'];
}

You can use !is_numeric() instead empty()
thanks for such a important note, Rafa

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'];
}

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

Related

How to treat zero values as true using php?

Here is my sample code:
$issue_id = $_POST['issue_id'];
if(!empty($issue_id)){
echo 'true';
}
else{
echo 'false';
}
If I pass 0 to $_POST['issue_id'] by form submitting then it echo false. Which I want is: Condition will be true if the following conditions are fulfilled:
1. true when I pass any value having 0.
2. false when I don't pass any value. i.e: $_POST['issue_id'] is undefined.
I also tried this:
if(!isset($issue_id)){
echo 'true';
}
else{
echo 'false';
}
if(!empty($issue_id) || $issue==0){
echo 'true';
}
else{
echo 'false';
}
The last one is okay, meaning if I pass any value having ZERO then it will echo true. But it will also echo true if I don't pass any value. Any idea?
The last is okay, meaning if I pass any value having ZERO then it echo true. But it also echo true if I don't pass any value. Any idea?
if (isset($_POST["issue_id"]) && $_POST["issue_id"] !== "") {
}
please notice I used !== not !=. this is why:
0 == "" // true
0 === "" // false
See more at http://php.net/manual/en/language.operators.comparison.php
also if you are expecting number you can use
if (isset($_POST["issue_id"]) && is_numeric($_POST["issue_id"])) {
}
since is_numeric("") returns false
http://php.net/manual/en/function.is-numeric.php
Alternatively if you expect number good option is filter_var
if (isset($_POST["issue_id"]) {
$issue_id = filter_var($_POST["issue_id"], FILTER_VALIDATE_INT);
if ($issue_id !== false) {
}
}
since filter_var("", FILTER_VALIDATE_INT) will returns false and filter_var("0", FILTER_VALIDATE_INT) will return (int) 0
http://php.net/manual/en/function.filter-var.php
if(isset($_POST['issue_id'])) {
if($_POST['issue_id'] == 0) {
echo "true";
}
else {
echo "false";
}
}
When you get data from a form, remember:
All text boxes, whether input or textarea will come as strings. That includes empty text boxes, and text boxes which contain numbers.
All selected buttons will have a value, but buttons which are not selected will not be present at all. This includes radio buttons, check boxes and actual buttons.
This means that $_POST['issue_id'] will be the string '0', which is actually truthy.
If you need it to be an integer, use something like: $issue_id=intval($_POST['issue_id']);
#Abdus Sattar Bhuiyan you can also full fill your two condition like below one:
<?php
$_POST["issue_id"] = "0";
$issue_id = isset($_POST['issue_id']) ? (!empty($_POST['issue_id']) || $_POST['issue_id'] === 0 || $_POST['issue_id'] === "0") ? true : false : false;
if($issue_id){
echo 'true';
}
else{
echo 'false';
}

Which function should I use to detect empty values in a form POST?

I don't want to import blank/empty, space, null value on my database. So for this reason I want to check my input value before importing on database. Please any one can tell me isset and empty function which one is good for checking input value. here is my code. Thanks
$required = array('login', 'password', 'confirm', 'name', 'phone', 'email');
$error = false;
foreach($required as $field) {
if (empty($_POST[$field])) {
$error = true;
}
}
if ($error) {
echo "All fields are required.";
} else {
echo "Proceed...";
}
In this situation empty makes more sense, because it also checks whether the string is empty. isset just checks whether if it is defined. You might also want to trim the input.
$required = array('login', 'password', 'confirm', 'name', 'phone', 'email');
$error = false;
foreach($required as $field) {
if (empty($_POST[$field]) || strlen(trim($_POST[$field])) == 0) {
$error = true;
}
}
if ($error) {
echo "All fields are required.";
} else {
echo "Proceed...";
}
isset is totally useless and empty is perhaps not an appropriate choice here.
The values inside $_POST (and also $_GET and $REQUEST) are always typed as strings, so isset will always return true. Additionally, the behavior of empty on false, null and other such values does not come into play, which means that the empty check will only reject:
zero-length strings
the string "0"
This is different from what your code seems to intend to reject, which would be:
zero-length strings
strings composed entirely of whitespace
Consider using trim($_POST['foo']) === '' as the condition instead.
The best way might be using empty and trim. Why trim? It will remove the spaces and lines etc. from the beginning and the end. That means, when someone inserts a few spaces but no text, the spaces can be removed so you can check empty:
if(empty(trim($foo)))
{
// It is empty!
}
Isset() checks if a variable has a value including ( Flase , 0 , or Empty string) , But not NULL.
Returns TRUE if var exists; FALSE otherwise.
empty() function checks if the variable has an empty value empty string , 0, NULL ,or False. Returns FALSE if var has a non-empty and non-zero value.
Example:
$var = 0;
// Evaluates to true because $var is empty
if (empty($var)) {
echo '$var is either 0, empty, or not set at all';
}
// Evaluates as true because $var is set
if (isset($var)) {
echo '$var is set even though it is empty';
}
The source
In your case, you can use empty() function
Fix it:
foreach($required as $field)
{
$val = trim($_POST[$field];
if (empty($val))
{
$error = true;
}
}
You could incorporate isNotEmpty function
<?php
function isNotEmpty($input){
$strTemp = trim($input);
if($strTemp !== ''){
return true;
}
return false;
}
?>
Save isNotEmpty as 'isnotempty.php' encase you need to reference it in the future.
include 'isnotempty.php';
$error = false;
foreach($required as $field) {
if (!(isNotEmpty($_POST[$field]))) {
$error = true;
}
if ($error) {
echo "All fields are required.";
} else {
echo "Proceed...";
}
Hope this helps

PHP not showing error when I put only single = in if condition

My code as follows:
if($_POST['user_id'] = ''){
//some statement;
}
In the above if condition I have put only single =. PHP is not showing any error but I am getting a white blank page. Does anyone has any clue?
if($_POST['user_id'] = '') means:
$_POST['user_id'] becomes '' .. if ('') // always false
if($_POST['user_id'] == '') means:
$_POST['user_id'] compares to '' .. if ( comparison)
Not sure if trolling or real question...
you said it yourself, you're using a single =. You need 2 to check for equality.
if($_POST['user_id'] == ''){
//some statement;
}
When you use a single equal sign, you're basically "set $_POST['user_id'] to '', then test if it's true). Since '' evaluates to false, you get nothing.
This:
if($_POST['user_id'] = ''){
Tries to assign an empty string to $_POST['user_id']. This:
if($_POST['user_id'] == ''){
Is a comparison. You should almost always be doing the second one - the first one over-rides the value in $_POST, and returns the value of the assignment.
try it
Use it
$user_id = $_POST['user_id'];
if($user_id == ''){
//some statement;
}
inseted of
if($user_id = ''){
//some statement;
}
Or try another one
$user_id = $_POST['user_id'];
if(isset($user_id) && !empty($user_id)){
//some statement;
}
It's not triggering any error because it is a valid condition.
if($_POST['user_id'] = '')
equals to
$_POST['user_id'] = '';
if($_POST['user_id']){
//Boolean comparison of a string. Empty = false. Not empty = true.
}
An example of use:
function division($var1, $var2){
if($var2 > 0){
return $var1/$var2;
return false;
}
if($result = division(50,2)){
//It returned 25 which is true!
}
if(!$result = division(50,0)){
//Returned FALSE because you can't divide by zero!
}

make an ifnot statement and if statement in one line

I'm trying to make an if statement with 2 conditions. One that checks if one variable is NOT present & does NOT matches the word "good2go" and the other that checks to make sure "body" variable is present. I'm trying to trip the error message here. Here is what I have and what I've tried, and none of it seems to work.
if (stripos($_POST['check'], 'good2go') == FALSE && $_POST['body']) {
$error = true; }
if (!$_POST['check'] == 'good2go' && $_POST['body']) {
$error = true; }
if (!stripos($_POST['check'], 'good2go') && $_POST['body']) {
$error = true; }
if ((!stripos($_POST['check'], 'good2go')) && $_POST['body']) {
$error = true; }
How do I get this to work?
here's the entire code of contact_us.php this has the validation code and the email code.
$error = false;
if (isset($_GET['action']) && ($_GET['action'] == 'send')) {
// Winnie the pooh check
//$t = tep_db_prepare_input($_POST['verify']);
if (!isset($_POST['check']) && !$_POST['check']=='good2go' && isset($_POST['body'])) {
$error = true;
} else { // Winnie the pooh Check
$name = tep_db_prepare_input($_POST['name']);
$email_address = tep_db_prepare_input($_POST['email']);
//IP recorder start
$ipaddress = $_SERVER["REMOTE_ADDR"];
$ip = "\n\nIP: " . $ipaddress;
$content = "\n\nName: ".$name."\n\nComments: ".$_POST['enquiry'];
$product = tep_db_prepare_input($_POST['product']);
if ($product) {
$product_text = "\n\nProduct Interest: ".$product; }
$content_ip = $content . $product_text. $ip;
$enquiry = tep_db_prepare_input($content_ip);
//IP recorder end
}
// BOF: Remove blank emails
// if (tep_validate_email($email_address)) {
// tep_mail(STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS, EMAIL_SUBJECT, $enquiry, $name, $email_address);
// tep_redirect(tep_href_link(FILENAME_CONTACT_US, 'action=success'));
// } else {
// $error = true;
// $messageStack->add('contact', ENTRY_EMAIL_ADDRESS_CHECK_ERROR);
if (! tep_validate_email($email_address)) {
$error = true;
$messageStack->add('contact', ENTRY_EMAIL_ADDRESS_CHECK_ERROR);
}
if ($enquiry == '') {
$error = true;
$messageStack->add('contact', ENTRY_EMAIL_CONTENT_CHECK_ERROR);
}
if ($error == false) {
tep_mail(STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS, EMAIL_SUBJECT, $enquiry, $name, $email_address);
tep_redirect(tep_href_link(FILENAME_CONTACT_US, 'action=success'));
// EOF: Remove blank emails
}
}
Solution to your updated problem:
if (!isset($_POST['check']) || !$_POST['check']=='good2go' || !isset($_POST['body'])) {
$error = true;
}
The reason for the pipes vs ampersands is that you want to throw an error if ANY of the fields has issue. Also, you want to check if body is NOT set vs IS set. Glad this worked out for you!
and the other that checks to make sure "body" variable is not present.
if(stripos($_POST['check'], "good2go") !== false && !isset($_POST['body'])){
//code here
}
According to PHP docs regarding the stripos function:
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.
So you need to change the first line to:
// Doing stripos checks you MUST use === (not ==)
if (stripos($_POST['check'], 'good2go') !== FALSE && $_POST['body']) {
$error = true; }
And to check if there is no $_POST['body'] you can change the above to:
if (stripos($_POST['check'], 'good2go') !== FALSE && (!isset($_POST['body'])) {
-- Update --
According to your comment, you need $_POST['check'] to equal 'good2go', then you shouldn't be using stripos as it will check for the existence of good2go regardless if it's exactly equal, or part of a string; 'wow this hamburger is good2go'.
So I would change the conditional to:
if (((isset($_POST['body'])) && (strlen($_POST['body']) > 0)) && ((!isset($_POST['check'])) || ($_POST['check'] !== 'good2go'))) {
// Post body has a value and Post check DOES NOT equal good2go, someone is hax0rin!
}
You may want to read up on Cross-site request forgery as it seems right inline with what you are working on.
One that checks if one variable is present & matches the word "good2go"
isset($_POST['check']) AND $_POST['check'] == 'good2go'
and the other that checks to make sure "body" variable is not present.
!isset($_POST['body'])
so, just put them together
if (isset($_POST['check']) AND $_POST['check'] == 'good2go' AND !isset($_POST['body'])) {
$error = true;
}
try this:
if(!empty($_POST['check']) && $_POST['check']=='good2go' && empty($_POST['body'])) { $error=true; }
Consider using empty instead of isset if your $_POST['body'] can be present with an empty value.
No need for all those unneeded functions. What you are trying to achieve is:
if (isset($_POST['check']) && $_POST['check']=='good2go' && !isset($_POST['body']) {
// your code
}
However, As per the title of the question: Use a ternary statement. Syntax is as such
$var = <condition> ? <true> : <false>;

Javascript; check if a variable is 1 or 0

I'm using a variable in Javascript which will be set via Php e.g. var usesInterview = <?php echo 1;?>
If not, then var usesInterview = <?php echo 0;?>
How best should I handle this in my code? There will be a If statement to check for the variable and determine the route to take.
I've tried using typeof() == 1 and when I set it to 0, it still carries out the routine as if it where 1.
Why not set it with javascript:
usesInterview = 1;
Even if you set it with PHP, you can check like this:
if (usesInterview === 1){
// variable is equal to 1
}
else if (usesInterview === 0){
// variable is equal to 0
}
Notice the === to check for both type as well as value. If you don't want to check for type, you need to use == like this:
if (usesInterview == 1){
// variable is equal to 1 or "1" or true
}
else if (usesInterview == 0){
// variable is equal to 0 or "0" or "" or false
}
You should avoid the later approach when you are sure about both type as well as value.
More Information:
http://w3schools.com/JS/js_comparisons.asp
There are so many ways you can do it... Ie
var usesInterview = <?php echo [0|1];?>
usesInterview ? goingTrueWay() : goingFalsegWay();
or
<?php echo [0|1];?> ? goingTrueWay() : goingFalseWay();
or something like this:
var waysCollection = {
0: function () {...} //routine for usesInterview == 0
1: function () {...} //routine for usesInterview == 1
}
waysCollection[<?php echo [0|1];?>]();
also you can use one of the early suggestion:
if (<?php echo [0|1];?>) {
// truthy branch
} else {
// falsy branch
}
BTW, if you want usesInterview to be a boolean, yes/no trigger, - use true/false not 0/1. Its easier to read and understand later. For ex
var usesInterview = <?php echo [false|true];?>
if (usesInterview) {
//do this if `true`
} else {
//do this if `false`
}
typeof will return the type of the value - "number" in this case. You're using a non-strict equality check (==) so "number" == 1 is true.
Just check the value, using type-strict equality operator (===):
if (usesInterview === 1) {
// do something
}
else if (usesInterview === 0) {
// do something else
}
Read more about JavaScript comparison operators at https://developer.mozilla.org/en/JavaScript/Reference/Operators/Comparison_Operators.
When usesInterview is 1 it's truthy. So it's as simple as:
if (usesInterview) {
// truthy branch
} else {
// falsy branch
}

Categories