The script in Listing 11.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 value. 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 assignment 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 (if $_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, 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 saves the incremented value of $num_tries: <input type="hidden" name="num_tries" value="<?php echo $num_tries; ?>"/> Listing 11.7 shows the new script in its entirety. Listing 11.7. Saving State with a Hidden Field
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 1 each time you access the form. |