02-15-2012, 04:50 AM
|
#3 (permalink)
|
|
The Addict
Join Date: Aug 2008
Posts: 336
Thanks: 8
|
The thing about web development is that it is stateless due to the nature of http requests. Meaning that you can't save state between requests (for example when you submit a form or click on a link). There is a few things you can do here to save the random number between requests, you can use a cookie to save it and then obtain it later, another would be using sessions (which sometimes are implemented using cookies). The cookies are saved on the client while the sessions are most of the time saved in client and sometimes in server. But on the server side you can also save it in a database or a local file.
Or you can also use the hidden input tag to keep it in the between requests.
The next is an example of how it would look using the hidden input. Just gotta make sure the
PHP Code:
<?php$message = "What number am I thinking of?"; $num = $_POST[ 'num'] ? $_POST[ 'num'] : rand(0, 100); if (isset($_POST[ "submit"] )) { $num = $_POST[ 'num']; if ($_POST[ 'guess'] > $num) { $message = "Too high, guess again!"; } elseif ($_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"/> <input type= "hidden" name= "num" value= "<?php echo $num ?>" /> <p><input type= "submit" name= "submit" value= "Submit"/></p> </form> <?php echo isset($_POST[ 'submit'] ) ? $num : ''; ?></body> </html>
|
|
|
|