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

3
  • 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) Commented Mar 12, 2016 at 12:37
  • 1
    $Iusername = $_POST['username']; remove it, because you have it in if(isset($_POST['submit'])){ condition and that is enough Commented Mar 12, 2016 at 12:38
  • 1
    Possible duplicate of PHP: "Notice: Undefined variable" and "Notice: Undefined index" Commented Mar 12, 2016 at 12:55

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.