ilikecake1
ilikecake1

Reputation: 41

Random number generator game in PHP using a form

I am trying to create a webpage that prompts the user to guess a number from 1 to 5 which is randomly generated and stored in the form.

Then, when the form is submitted, the guess is checked against the random number and if the guess is incorrect, the user is prompted to guess again but the random value stays the same with each guess.

My issue is that once the user submits the form, the random number is not showing up when the user is prompted to try again.

else if (isset($_POST["firstname"])) {
    echo $_POST['firstname'] . $_POST['lastname'];
    echo "Hi " . $_POST['firstname'] . " " . $_POST['lastname'] . "!";
    ?>
    <html>
        <form name="number" action="random.php" method="post">
            <p>Enter a guess: <input type="text" name="guess" /></p>
            <input type="hidden" name="numtobeguessed" value="<?php echo $_POST["numtobeguessed"]; ?>" ></p>
            <input type="submit" value="Guess!" />
        </form>
    </html>
    <?php
    $_POST["numtobeguessed"] = rand(1, 5);
    $guessed = $_POST["numtobeguessed"];
    echo "Number to be guessed " . $guessed;

} else if (isset($_POST["guess"])) {
    if ($_POST["guess"] != $_POST["guessed"]) {
        echo $_POST["guess"] . " is not correct";
        ?>
        <form name="number1" action="random.php" method="post">
            <p>Enter a guess: <input type="text" name="guess" /></p>
            <input type="hidden" name="numtobeguessed" value="<?php echo $_POST["guessed"]; ?>" ></p>
            <input type="submit" value="Guess!" />
            <?php
        }
    }
    ?>

Upvotes: 2

Views: 2076

Answers (1)

Guffa
Guffa

Reputation: 700362

You are sending the value in a field with the name numtobeguessed but you try to read it with the name guessed.

This:

if ($_POST["guess"] != $_POST["guessed"]) {

should be:

if ($_POST["guess"] != $_POST["numtobeguessed"]) {

and this:

<input type="hidden" name="numtobeguessed" value="<?php echo $_POST["guessed"]; ?>" ></p>

should be:

<input type="hidden" name="numtobeguessed" value="<?php echo $_POST["numtobeguessed"]; ?>" ></p>

Upvotes: 1

Related Questions