0

Here is the code, it is telling me I have an undefined index which is weird because I already defined it with HTML code. Any way around this error? or any ways to make it better would be much appreciated...

<h1>make a username</h1>
<form method="post" action="<?php echo  
htmlspecialchars($_SERVER["PHP_SELF"]); ?>"> 
Username: <input type="text" name="username" value="<?php echo $username; ?>">
<br><br>
<input type="submit" name="submit" value="Submit"> 
</form>

<?php 

$username = $_POST["username"];

echo $username;

?>
1
  • Use isset() and initialize the variable $username at start with empty value Commented Apr 15, 2016 at 5:31

5 Answers 5

1

$_POST["username"] will only be defined after you submit the form. When you first load the page (with an http GET), $_POST["username"] will be undefined.

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

Comments

0

After form submission it will work. You should try this:

<?php 
    if(isset($_POST["username"])){
        $username = $_POST["username"];
    }

?>

<h1>make a username</h1>
<form method="post" action="<?php echo  
htmlspecialchars($_SERVER["PHP_SELF"]); ?>"> 
Username: <input type="text" name="username" value="<?php echo (isset($username))? $username: ''; ?>">
<br><br>
<input type="submit" name="submit" value="Submit"> 
</form>

<?php
    echo (isset($username))? $username: '';
?>

Comments

0

Do following changes to your code :

<h1>make a username</h1>
<form method="post" action="<?php echo  
htmlspecialchars($_SERVER["PHP_SELF"]); ?>"> 
Username: <input type="text" name="username" value="<?php echo $username; ?>">
<br><br>
<input type="submit" name="submit" value="Submit"> 
</form>

<?php 
/// This portion of code will execute only after you hit submit button
if(isset($_POST['username']))
{
$username = $_POST["username"];

echo $username;
}
?>

Comments

0

if ( isset( $_POST["username"] ) ){

$username = $_POST["username"];

} else{

$username = '';

}
echo $username;

Try this code instead of your php code. This may help you.

Comments

0

$_POST["username"]; add an @ before this,@$_POST['username'],'@' will ignore this error

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.