开发者

PHP can't iterate through too high or too low

开发者 https://www.devze.com 2022-12-11 07:15 出处:网络
[Disclaimer: I am new to PHP, and I am just learning, so please no flamers, it reallyhinders the learning process when one is trying to learn, thank you.]

[Disclaimer: I am new to PHP, and I am just learning, so please no flamers, it really hinders the learning process when one is trying to learn, thank you.]

The code below runs, the only problem is that it does not tell the user when the number is too high or too low, I am doing something wrong, but I can't see the error?

<?php
//Starts our php document
if (!$number)
//if we have already defined number and started the game, this does not run开发者_Python百科
{
 Echo"Please Choose a Number 1-100 <p>";
//gives the user instructions
$number = rand (1,100) ;
//creates number
}

else {
//this runs if the game is already in progress
if ($Num >$number)
{
Echo "Your number, $Num, is too high. Please try again<p>";
}
//if the number they guessed is bigger than number,  lets user know,  guess was  high

elseif ($Num == $number)
{
Echo "Congratulations you have won!<p>";
//if the number they guessed was correct it lets them know they won
Echo "To play again, please Choose a Number 1-100 <p>";
$number = rand (1,100) ;
//it then starts the game again by choosing a new value for $number that they can guess
}

else
{
Echo "Your number, $Num, is too low. Please try again<p>";
}
//if the answer is neither correct or to high, it tells them it is too low
}
?> 

<form action = "<?php Echo $_SERVER[’PHP_SELF’]; ?>" method = "post"> <p>
<!--this sends the form back to the same page we are on-->

Your Guess:<input name="Num" />
<input type = "submit" name = "Guess"/> <p>
<!--Allows the user to input their guess-->

<input type = "hidden" name = "number" value=<?php Echo $number ?>>
<!--keeps passing along the number value to keep it consistent till it is guessed-->

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


I am assuming $Num is undefined and I am assuming you are assuming it will be defined be cause it is defined in the form.

Try this at the start of your script:

if(!empty($_POST)) {
    $Num = (int) $_POST['Num'];
}


$number is not automatically set to the value the <input> field has. (It was in early versions of PHP). You now have to use $_POST['number'] and $_POST['Num'] for this.


register_globals in your php.ini is probably Off (and that's a good thing) and therefore you can only access those variables through $_POST['Num'] and $_POST['number'] (you can just assign $number=$_POST['number'] at the beggining of your script)

also, sending the secret $number through form is not nice, you might want to read about php sessions


Suggestions:

1) use echo, not Echo

2) do not forget to close the p tag

0

精彩评论

暂无评论...
验证码 换一张
取 消