Is entering 0 in the field registered as empty?

Here is my code:

if (isset($_POST['addmonths'])){
    if (!empty($_POST['months'])){
        if (is_numeric($_POST['months'])){
            $monthstoadd = $_POST['months'];
            if ($monthstoadd < 1){
                mysql_query("UPDATE users SET months='lifetime' WHERE username='$lookupuser'");
                echo "Successfully set " . $lookupuser . " to lifetime";
            }elseif ($monthstoadd > 0){
                $monthstoadd = $monthstoadd*2592000;
                mysql_query("UPDATE users SET months=months+'$monthstoadd' WHERE username='$lookupuser'");
                echo "Successfully added " . $_POST['months'] . " months to " . $lookupuser . " paid time.";
            }else{
                echo "Error.";
            }
        }else{
            echo "Months need to be numeric. If you're trying to set lifetime, use 0.";
        }
    }else{
        echo "You didn't enter anything.";
    }
}

When I enter 0, it should set the user for life, but instead he just echos You didn't enter anything.Not sure how to fix it. Any ideas?

+3
source share
3 answers

You need to check the type to make sure it is empty, not the registers as empty with ===.

if ($_POST['months'] !== ''){

This checks if it matches exactly empty. If it does not pass.

0
source

Is entering 0 in the field registered as empty?

Yes Yes. From the docs toempty :

The following things are considered empty:

"( )
0 (0 )
" 0" (0 )
NULL

array() ( )
var $var; ( , )

?

empty , ( - ). , , , , , trim :

if (trim($_POST['months']) != ''){

$_POST['months] , , , .

+2

, empty isset ( false null) array_key_exists ( ).

if (!isset($_POST['months']) || $_POST['months'] === "")

if (!array_key_exists('months', $_POST) || $_POST['months'] === "")

Since this is POST data, it nullwill never be a value (the browser may either not send the input or send an empty string, which PHP translates to ""). Consequently, issetand array_key_existsinterchangeably. issethowever, it is preferable because it is not a function and therefore works faster (not to mention writing it faster).

+1
source

Source: https://habr.com/ru/post/1752087/


All Articles