Home > database >  PHP Code first saves the input, but when clicked on another button it doesn't save it anymore
PHP Code first saves the input, but when clicked on another button it doesn't save it anymore

Time:09-29

I wrote a Rock Paper Scissors code that first gets the input of player 1, it supposed to save it and then asks for the input of player 2, saves it and outputs the inputs of both the players. But right now it only outputs the input of player 2, but if you enter the first input it still saves it, but after entering the second one is just doesn't save it anymore. Could someone please help me fix this?

<?php
if (!isset($keuze1)) {
    echo "
    <form method='GET'>
    <input type='submit' name='knop' value='Begin met spelen'></button>
    </form>
";
}

$knop = '';

if (isset($_GET['knop'])) {
    echo "
    <h2>Speler 1</h2>
    <form method='GET'>
    <select name='speler1'>
    <option value='steen'>Steen</option>
    <option value='papier'>Papier</option>
    <option value='schaar'>Schaar</option>
    </select>
    <input type='submit' name='keuze1' value='kiezen'>
    </form>;
    ";
}

$keuze1 = '';
$keuze2 = '';

if (isset($_GET['keuze1'])) {
    $keuze1 = $_GET['speler1'];
    echo "
    <h2>Speler 2</h2>
    <form method='GET'>
    <select name='speler2'>
    <option value='steen'>Steen</option>
    <option value='papier'>Papier</option>
    <option value='schaar'>Schaar</option>
    </select>
    <input type='submit' name='keuze2' value='kiezen'>
    </form>
    ";
} 

if (isset($_GET['keuze2'])) {
    $keuze2 = $_GET['speler2'];
    echo "
    Speler 1 koos $keuze1 en Speler 2 koos $keuze2
    ";
}

echo $keuze1;
?>

CodePudding user response:

Every time you submit a form, the script starts over, and nothing is "saved" from one iteration to the next. So when you click the <input type='submit' name='keuze2' value='kiezen'> button, everything is reset and the only variables you have are the ones that are submitted in the form.

So if you want to bring $keuze1 along, the easy way to do that is to pass it into a hidden form field, like this:

if (isset($_GET['keuze1'])) {
    echo "
    <h2>Speler 2</h2>
    <form method='GET'>
    <input type='hidden' name='speler1' value=" . htmlspecialchars($_GET['speler1']) . " />
    <select name='speler2'>
    <option value='steen'>Steen</option>
    <option value='papier'>Papier</option>
    <option value='schaar'>Schaar</option>
    </select>
    <input type='submit' name='keuze2' value='kiezen'>
    </form>
    ";
}

... and then, get $keuze1 from $_GET['speler1'] in your final if block, before outputting it.

  •  Tags:  
  • php
  • Related