Using Hidden Fields to Save State

The script in Listing 9.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. Listing 9.7 adds a hidden field to the number-guessing script and some PHP to work with it.

Listing 9.7. Saving State with a Hidden Field
 1: <?php 2: $num_to_guess = 42; 3: $num_tries = (isset($_POST[num_tries])) ? $num_tries + 1 : 0; 4: $message = ""; 5: if (!isset($_POST[guess])) { 6: $message = "Welcome to the guessing machine!"; 7: } else if ($_POST[guess] > $num_to_guess) { 8: $message = "$_POST[guess] is too big! Try ...

Get Sams Teach Yourself PHP, MySQL® and Apache All in One now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.