0

When I use the GET method in php program.. I face the error as Notice:

Undefined index: name in /opt/lampp/htdocs/aj/getmethod.php on line 2

The error is shown on line 2, name and age.

<?php
if($_GET["name"]||$_GET["age"])
{
    echo "welcome ".$_GET["name"]."<br/>";
    echo "You are ".$_GET["age"]."Years old";
}
?>
<html>  
<body>
<form action="<?php $_PHP_SELF ?>" method="GET">
Name : <input type="text" name="name"/>
Age : <input type="text" name="age"/>
<input type="submit" />
</form>
</body>
</html> 
Alberto
  • 674
  • 13
  • 25

2 Answers2

0

may be you should just chage that to :

if(isset($_GET["name"]) && isset($_GET["age"])){
    echo "welcome ".$_GET["name"]."<br/>";
    echo "You are ".$_GET["age"]."Years old";
}

But you need to add some validations

Yassine
  • 76
  • 1
  • 8
  • @akatheesanajay If this answer solved your question could you please accept it as answer, so other people can quickly find the solution should they face the same problem? And also to give reputation to Yassine. – brombeer Sep 28 '18 at 10:29
0

You may want to check if the variables are set before accessing them. Additionally, you are echoing the values before starting the tag, this means that the name and age values will be written at the very top of the page (or even hidden, depending on your CSS rules).

To fix it, you can use this code:

<html>  
<body>
<form action="<?php echo $_PHP_SELF ?>" method="GET">
Name : <input type="text" name="name"/>
Age : <input type="text" name="age"/>
<input type="submit" />
<br><br>
<?php
if(isset($_GET["name"]))
{
    echo "welcome ".$_GET["name"]."<br/>";
}
if(isset($_GET["age"]))
{
    echo "You are ".$_GET["age"]."Years old";
}
?>
</form>
</body>
</html> 

In this way, you'll be writing the values right below the form, only if the value was set.

Alberto
  • 674
  • 13
  • 25