I'm a little confused about session variables... the following code example displays an error if the text entered does not equal "test" but the form field value is blanked out. I'm pretty sure I need to save the value in a session variable but I'm confused as to how to do it.

<HTML>
<HEAD>
</HEAD>
<BODY>

<?php

if ($submit) {

if ($text == "test") {
$error="N";
}else{
$error="Y";
}

} else {

}
?>

<form method="post" action=" <?php echo $PHP_SELF ?> ">
<INPUT TYPE="text" NAME="text" SIZE="4" MAXLENGTH="4">
<input type="submit" name="submit" value="Test">
</FORM>

<?php
if ($error == "Y") {
echo"only "test" is a valid value";
}
?>

</BODY>
</HTML>


Thanks for any help

    First of all, why do you immediately close the Else block:

    <?php
    
    if ($submit) {
    
    if ($text == "test") {
    $error="N";
    }else{
    $error="Y";
    }
    
    } else {
    
    }
    ?>
    

    If you don't want to have an alternate code block, just omit the else block. If you're intention is to have the HTML after you end that php block display only if $text is not == "test", you omit that last }.

    You should also change

    echo"only "test" is a valid value";

    to

    echo "only \"test\" is a valid value";

    Also, you should probably change references to form variables like $submit to $_POST['submit']; for better compatibility with future versions of php.

      I take your points but the actual question of the thread is still unanswered......

      The value in the text box is blanked out when the error is displayed.

        Sorry, let me see if I can figure out exactly what you want... You want to have a form where the user can enter a value, and one is valid and everything else gives an error. So you want the form to have the previous value the user entered if they enter something aside from "test"? If not, please explain more clearly and I'll see if I can help.

          Thats it.

          I want the invalid value to still be in the text box.

          Thanks

            Ok, for that, I think all you'd need to do is to change:

            <INPUT TYPE="text" NAME="text" SIZE="4" MAXLENGTH="4">

            to:

            <INPUT TYPE="text" NAME="text" SIZE="4" MAXLENGTH="4" <?PHP if ($text) echo "VALUE=\"$text\"" ?>>

            To have a value pre-set in a text box in a form, you use the VALUE element, and this embedded PHP code adds that if there's already a $text value.

              Thanks very much.. that worked beautifully!

              Just thought I'd better put a correct syntax version in case anybody else comes across this post...

              <input type="text" name="text" size="4" maxlength="4" value=" <?PHP if ($text) { echo"$text"; } ?> ">

              Thanks once again 🙂

                Ok, glad I could help 🙂

                  Write a Reply...