'Little problem with HTML form and input tags and with PHP get method (Warning: Undefined array key) [duplicate]
I am trying to get some basic information from the user -
<body>
<form action = "index.php" method="get">
Name: <input type="text" name="username">
<br>
Age: <input type="number" name="age">
<input type="submit">
</form>
<br>
Your name is <?php echo $_GET["username"] ?>
<br>
Your age is <?php echo $_GET["age"] ?>
</body>
This code is functional, but when I look to the browser prior to filling in the name and age, there is kind of a glitch, which can be seen underneath the submit button.
Your name is
Warning: Undefined array key "username" in path\index.php on line 15
Your age is
Warning: Undefined array key "age" in path\index.php on line 17
However, when I enter in some information, then that error disappears, but it would be nice, if it was not there in the first place.
Could anybody give me any advice on how to fix this bug?
Solution 1:[1]
Wrap your echo under isset() condition. It will prevent the execution of the code if $_GET["username"] is not set or in other words, it will prevent the display if the form is not submitted(like on page load)
if(isset($_GET["username"])){
echo $_GET["username"];
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tushar |
