Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial


Adam maitland
Adam maitland
Courses Plus Student 211 Points

Carrying a php variable into a form when validation detects error ?

I have a form that looks like this

<form method="post" action="index.php">

    <lable id="newName">Choose a user name:</lable>  
    <input type="text" id="newName" name="newName">
    <p class="error"> <?php echo $error = ""; ?> </p>

    <lable id="newPassword">Choose a password:</lable>  
    <input type="text" id="newPassword" name="newPassword">
    <p class="error"> <?php echo $error = ""; ?> </p>

    <input name="submit" type="submit" value="Submit">


and php that looks like this


        if($_SERVER['REQUEST_METHOD'] == "POST") {

        $newName = $_POST['newName'];
        $newPassword = $_POST['newPassword'];

         if(empty($_POST['newName'])) {

          $error = "You must enter a user name!";




What should happen is when a user clicks send without entering anything into the form f the variable $error with in the form will be passed a string but this isn't working ?

1 Answer

Do you have the form HTML set correctly before your submit button/form text to direct itself to your PHP code? i.e.,

<form action="" method="post">

Then, in your PHP code within the HTML, you'd want to make sure that the error message is set before echoing it out:

 <lable id="newPassword">Choose a password:</lable>  
    <input type="text" id="newPassword" name="newPassword">
    <?php if(isset($error)) { 
         echo "<p class='error'>$error</p>"; 
          } ?>