-5

I want to enter a number between 1 and 10 in my form but I have an error message: Notice: Undefined index: level in. My variable $_GET['level'] does not exist?

else if(isset($_GET['level']) && !is_numeric($_GET['level']))
    {
        $code_error = 2;
        $message = "The level must be numeric ! ";
    }

    else if ($_GET['level'] < 1 || $_GET['level'] > 10 )
    {
        $code_error = 3;
        $message = "The level must be between 1 and 10 ";

    }

In html I have this:

echo '<label for="level">Level : </label>';
    if(isset($_GET['level']))
    {
        echo '<input type="text" id="level" name="level" value="'.$_GET['level'].'" >';
    }
    else
    {
        echo '<input type="text" id="level" name="level" >';
    }
    echo '<input type="submit" value="ok">'; 
julia
  • 3
  • 2

3 Answers3

0

Set a variable $level = $_GET['level']; and use it instead of $_GET['level'].

Correct code is:

$level = $_GET['level'];

echo '<label for="level">Level : </label>';
    if(isset($level))
    {
        echo '<input type="text" id="level" name="level" value="'.$level.'" >';
    }
    else
    {
        echo '<input type="text" id="level" name="level" >';
    }
    echo '<input type="submit" value="ok">'; 
Gabor
  • 566
  • 5
  • 14
0

Your problem is that you are calling isset on $_GET['level'], This means it tries to evaluate $_GET['level'] to find if it is set.

For an array element, you need to use array_key_exists('level', $_GET) which finds out if there is an element without trying to evaluate it.

Have a look here for some "related discussion"

Dragonthoughts
  • 2,180
  • 8
  • 25
  • 28
0

On this line...

else if ($_GET['level'] < 1 || $_GET['level'] > 10 )

like in the previous test where you check is set before checking it's numeric, you need to check it here as well...

else if (isset($_GET['level']) && ($_GET['level'] < 1 || $_GET['level'] > 10 ))

or restructure the code something like...

else if (isset($_GET['level'])) {
    if (!is_numeric($_GET['level']))
    {
        $code_error = 2;
        $message = "The level must be numeric ! ";
    }

    else if ($_GET['level'] < 1 || $_GET['level'] > 10 )
    {
        $code_error = 3;
        $message = "The level must be between 1 and 10 ";
    }    
}
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55