-2

before the first time that i clicking on "submit" the source looking like this (fine) :

    <html>
    <body>
    Guess a number between 1 and 100
    <form action="/www/lesson4/gueeANumber.php" method="GET">
        <input type="text" name="my_answer" autofocus>
        <input type="hidden" name="number" value="61">
        <br><br>
        <input type="submit" value="Submit">

    </form>
    </body>
    </html>

after the first submit :

Too Low<br>
<html>
<body>
Guess a number between 1 and 100
<form action="/www/lesson4/gueeANumber.php" method="GET">
    <input type="text" name="my_answer" autofocus>
    <input type="hidden" name="number" value="<br />
<b>Notice</b>:  Undefined variable: number in <b>C:\xampp\htdocs\www\lesson4\gueeANumber.php</b> on line <b>30</b><br />
">
    <br><br>
    <input type="submit" value="Submit">

</form>
</body>
</html>

and here's my entire code with the php :

<?php
if(!empty($_GET))
{
    if(isset($_GET['number'])){
        $guess=(int)$_GET['my_answer'];
        $num=(int)$_GET['number'];
        if($guess<$num){
        echo "Too Low"."<br>";
    }
        else if($guess>$num){
        echo "Too High"."<br>";
    }
        else{
        echo "Correct!";
            exit();
    }
    }
}
else
{
    $number=mt_rand(1,100);
}
?>

<html>
<body>
Guess a number between 1 and 100
<form action="<?php echo $_SERVER["PHP_SELF"];?>" method="GET">
    <input type="text" name="my_answer" autofocus>
    <input type="hidden" name="number" value="<?php echo $number?>">
    <br><br>
    <input type="submit" value="Submit">

</form>
</body>
</html>

the idea is that the user should guess a number between 1 and 100 and the code should tell him if its lower or higher, and all the time refresh the page, if he correct so we should exit.

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
evg
  • 11
  • 1
  • 2
  • So, where's the error? Although if I'll guess, you might be having the error after submitting the form, specifically `Undefined index: $number` – Carl Binalla Nov 21 '19 at 03:49

1 Answers1

0

You don't have a php variable called $number, which you are referring to in your html.

I believe you should be referring to $num.

Change

<input type="hidden" name="number" value="<?php echo $number?>">

to

<input type="hidden" name="number" value="<?php echo $num?>">
  • Actually, OP has `$number`, in the `else` part --> `$number=mt_rand(1,100);` – Carl Binalla Nov 21 '19 at 04:04
  • You're right. Now that I see it, the reason you get the error is because PHP knows that the variable $number may not get created, depending on the user input, so it will not allow you to use it in the html. You can work around it by adding a @ in front of $number in your html. – Barry Beach Nov 21 '19 at 23:16