Form Submit, keep variable?

Discussion in 'PHP' started by bobby9101, Mar 24, 2007.

  1. #1
    So I set up a simple little validation on a form.
    Say I create two variables each with a random number between 1 and 10.
    and then on my form I show: $x + $y = [ ] and make the user enter it.
    Then after the form is submitted it checks to see if $x + $y = $_POST['validation'];
    The problem is that when the form is submitted $x and $y are re-randomized.
    Because the page is loaded. How to I counter-act this? I don't want to put a hidden field on the form and have that submit the variable.
    +rep for help, thanks a lot
     
    bobby9101, Mar 24, 2007 IP
  2. ThreeGuineaWatch

    ThreeGuineaWatch Well-Known Member

    Messages:
    1,489
    Likes Received:
    69
    Best Answers:
    0
    Trophy Points:
    140
    #2
    Something like,

    if(!(isset($_POST['validation']))) {
    generate your random numbers
    }
     
    ThreeGuineaWatch, Mar 24, 2007 IP
  3. bobby9101

    bobby9101 Peon

    Messages:
    3,292
    Likes Received:
    134
    Best Answers:
    0
    Trophy Points:
    0
    #3
    doesn't work, because the page is reloaded so then it doesn't even create the random numbers
     
    bobby9101, Mar 24, 2007 IP
  4. TwistMyArm

    TwistMyArm Peon

    Messages:
    931
    Likes Received:
    44
    Best Answers:
    0
    Trophy Points:
    0
    #4
    You'll probably have to do it via sessions. Just see if the session variables are set and use them. If they're not, randomise and set them first.
     
    TwistMyArm, Mar 24, 2007 IP
    bobby9101 likes this.
  5. ThreeGuineaWatch

    ThreeGuineaWatch Well-Known Member

    Messages:
    1,489
    Likes Received:
    69
    Best Answers:
    0
    Trophy Points:
    140
    #5
    Ok, I assumed you'd stored them in a session variable and were asking about the logic. Something like this then,

    <?
    session_start();
    
    if((isset($_POST['number_sum'])) && (($_SESSION[x] + $_SESSION[y]) == $_POST[number_sum])){
    
    echo "Correct!  ". $_SESSION[x] . "+" . $_SESSION[y] . "=" . $_POST['number_sum'];
    
    }
    else {
            $_SESSION[x] = rand(0,10) + 1;
            $_SESSION[y] = rand(0,10) + 1;
    ?>
    <form method=POST action='<? echo $_SERVER[PHP_SELF];?>'>
    <? echo $_SESSION[x]; ?> +
    <? echo $_SESSION[y]; ?> = <input type=text size=2 name=number_sum>
    <input type=submit value=Submit>
    </form>
    <? } ?>
    Code (markup):
     
    ThreeGuineaWatch, Mar 24, 2007 IP
    bobby9101 likes this.
  6. bobby9101

    bobby9101 Peon

    Messages:
    3,292
    Likes Received:
    134
    Best Answers:
    0
    Trophy Points:
    0
    #6
    I got it working with some stealing a little of your code, thanks +rep for both of you
     
    bobby9101, Mar 24, 2007 IP