Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

PHP

Adam maitland
PLUS
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">

</form>

and php that looks like this

<?php

        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>"; 
          } ?>