Forum Moderators: coopster

Message Too Old, No Replies

Undefined index

Undefined index. i checked it already but i don't know what's wrong. the e

         

ShineJoyPacho

6:06 am on Oct 12, 2015 (gmt 0)

10+ Year Member



<html>
<head>
<title>Identify two numbers if Odd or Even</title>
</head>

<body>
Enter two numbers<br>
<form method="GET" name="formNew" action="GradeForm.php">
number 1 <input type="text" name="num1"><br>
number 2 <input type="text" name="num2"><br>
<input type="submit" name="btnAdd" value="Identify now">
</form>


<?php
$n1= $_GET['num1'];
$n2= $_GET['num2'];


if ($n1%2 == 0 and $n2%2 == 0)
{
echo "".$n1. " and " .$n2;
echo "All numbers are even numbers";
}
else if ($n1%2 == 0 and $n2%1 == 0)
{
echo "".$n1. " and " .$n2;
echo "First number is even, Second number is odd";
}
else if ($n1%1 == 0 and $n2%2 == 0)
{
echo "".$n1. " and " .$n2;
echo "First number is odd, Second number is even";
}
else if ($n1%1 == 0 and $n2%1 == 0)
{
echo "".$n1. " and " .$n2;
echo "All numbers are odd numbers";
}

?>

</body>

</html>




Undefined index. i checked it already but i don't know what's wrong.


Notice: Undefined index: num1 in C:\xampp\htdocs\GradeForm.php on line 16

Notice: Undefined index: num2 in C:\xampp\htdocs\GradeForm.php on line 17

whitespace

7:41 am on Oct 12, 2015 (gmt 0)

10+ Year Member Top Contributors Of The Month



You need some form validation...

$_GET['num1'] and $_GET['num2'] are only set when the form is submitted. When the page is first displayed they are not set. ie. the index is undefined.

At the very least you should be checking that the GET value is set before reading it. For example:


$n1 = isset($_GET['num1']) ? $_GET['num1'] : null;


But you then need to handle the situation when either $n1 or $n2 are NULL (or in fact not numbers at all). ie. the user has not yet submitted the form, or entered nonsense.

To check that the form is submitted you could check that $_GET['btnAdd'] is set, but you still need to check that all the required values are correctly submitted as well.