Using Hidden Fields to Save StateThe script in Listing 10.6 has no way of knowing how many guesses a user has made, but we can use a hidden field to keep track of this. A hidden field behaves exactly the same as a text field, except that the user cannot see it unless he views the HTML source of the document that contains it. Take the original numguess.php script, and save a copy as numguess2.php. In the new version, add a line after the initial assinment of the $num_to_guess variable: $num_tries = (isset($_POST[num_tries])) ? $num_tries + 1 : 1; This line initializes a variable called $num_TRies, and assigns a value to it. If the form has not yet been submitted ($_POST[num_tries] is empty), the value of the $num_TRies variable is 1 because we will be on our first attempt at guessing the number. If the form has already been sent, then the new value is the value of $_POST[num_tries], plus 1. The next change comes after the HTML level H1 heading: <p><strong>Guess number:</strong> <?php echo $num_tries; ?></p> This new line simply prints the current value of $num_tries to the screen. Finally, before the HTML code for the form submission button, add the hidden field. This field will save the incremented value of $num_TRies: <input type="hidden" name="num_tries" value="<?php echo $num_tries; ?>"> Listing 10.7 shows the new script, in its entirety. Listing 10.7. Saving State with a Hidden Field1: <?php 2: $num_to_guess = 42; 3: $num_tries = (isset($_POST[num_tries])) ? $_POST[num_tries] + 1 : 1; 4: if (!isset($_POST[guess])) { 5: $message = "Welcome to the guessing machine!"; 6: } else if ($_POST[guess] > $num_to_guess) { 7: $message = "$_POST[guess] is too big! Try a smaller number."; 8: } else if ($_POST[guess] < $num_to_guess) { 9: $message = "$_POST[guess] is too small! Try a larger number."; 10: } else { // must be equivalent 11: $message = "Well done!"; 12: } 13: $guess = $_POST[guess]; 14: ?> 15: <html> 16: <head> 17: <title> Saving state with a hidden field</title> 18: </head> 19: <body> 20: <h1><?php echo $message ?></h1> 21: <p><strong>Guess number:</strong> <?php echo $num_tries; ?></p> 22: <form action="<?php echo $_SERVER[PHP_SELF]; ?>" method="POST"> 23: <p><strong>Type your guess here:</strong> 24: <input type="text" name="guess" value="<?php echo $guess; ?>"> 25: <input type="hidden" name="num_tries" value="<?php echo $num_tries; ?>"> 26: <p><input type="submit" value="submit your guess"></p> 27: </form> 28: </body> 29: </html> Save the numguess2.php file, and place it in your Web server document root. Access the form a few times with your Web browser, and try to guess the number (pretend you don't already know it). The counter should increment by one, with each access. |