View Single Post
Old 02-14-2012, 04:35 PM   #1 (permalink)
bgs
The Visitor
 
Join Date: Feb 2012
Posts: 2
Thanks: 0
bgs is on a distinguished road
Default Creating a random number once and keeping it

Hi,

I'm just beginning to learn PHP (day 2) and I can't really seem to figure this one out. My idea is a simple number guessing game that works something like this:

$num = rand(0,100);

(Accept $guess from user input)

if $num < $guess echo 'too low' etc.

The form references itself and sends the guess via POST. My problem is that the random number is getting set each time. I come from a forms/console development background and this is the first time I've delved into web programming, so there's some element here regarding the 'session' that isn't quite straight in my head.

Please feel free to enlighten me, poke fun at my code, etc.! Thanks for your help.

This is my code. It's almost entirely lifted from "Sams Teach Yourself PHP, MySQL and Apache" but I've modified the functionality to attempt to use a random number.

Code:
<?php
	$num = rand(0,100);
	if (!isset($_POST["guess"]))
	{
		$message = "What number am I thinking of?";
	}
	else if ($_POST["guess"] > $num)
	{
		$message = "Too high, guess again!";
	}
	else if ($_POST["guess"] < $num)
	{
		$message = "Too low, guess again!";
	}
	else
	{
		$message = "Correct!";
	}
?>

<html>
<head><title>Number guess</title></head>
<body>
<?php echo $message ?>
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="POST">
<input type="text" name="guess" />
<p><input type="submit" value="Submit"/></p>
</form>
<?php echo $num ?> <!-- just so I can see the output -->
</body>
</html>
bgs is offline  
Reply With Quote