2

How do you get input from the text field in the following code?

<?php

echo "<form action='signup.php' method='POST'>";
echo "<input type='text' placeholder='Username' name='username'/>";
echo "<button type='submit' name = 'submit' value='Register' >Sign up</button>";
echo "</form>";

$servername = "localhost";
$username = "root";
$password = "";

// Create connection
$conn = new mysqli($servername, $username, $password,"vaccinations");
$Iusername = $_POST['username'];

if(isset($_POST['submit'])){
$Iusername = $_POST['username'];
echo $Iusername;
echo "whadddup";
}

?>

This is giving me username is an undefined index. I need to grab the inputted data in the text field that was echoed

hyhae
  • 43
  • 7
  • 1
    Right after `$conn`, you have `$Iusername = $_POST['username'];`. And for every time you access this code and don't submit the form (when you first access it), it will generate that warning. Simple fix: Remove that line, because you define it within the `if(isset($_POST['submit'])){` (no need to define it twice) – Qirel Mar 12 '16 at 12:37
  • 1
    `$Iusername = $_POST['username'];` remove it, because you have it in `if(isset($_POST['submit'])){` condition and that is enough – Alive to die - Anant Mar 12 '16 at 12:38
  • 1
    Possible duplicate of [PHP: "Notice: Undefined variable" and "Notice: Undefined index"](http://stackoverflow.com/questions/4261133/php-notice-undefined-variable-and-notice-undefined-index) – Qirel Mar 12 '16 at 12:55

1 Answers1

2

Just remove the first $Iusername = $_POST['username']; and it will work fine.

Explanation:-

Each time when your page is loaded the above line is going to execute. And since $_POST['username'] have no value at that time (because it will have value if and only if form submits), your above statement fails and give you the warning of Undefined Index.

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98