php_mysql_apache [Electronic resources] نسخه متنی

اینجــــا یک کتابخانه دیجیتالی است

با بیش از 100000 منبع الکترونیکی رایگان به زبان فارسی ، عربی و انگلیسی

php_mysql_apache [Electronic resources] - نسخه متنی

Julie C. Meloni

| نمايش فراداده ، افزودن یک نقد و بررسی
افزودن به کتابخانه شخصی
ارسال به دوستان
جستجو در متن کتاب
بیشتر
تنظیمات قلم

فونت

اندازه قلم

+ - پیش فرض

حالت نمایش

روز نیمروز شب
جستجو در لغت نامه
بیشتر
لیست موضوعات
توضیحات
افزودن یادداشت جدید







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 a smaller number";
9: } else if ($_POST[guess] < $num_to_guess) {
10: $message = "$_POST[guess] is too small! Try a larger number";
11: } else { // must be equivalent
12: $message = "Well done!";
13: }
14: $guess = $_POST[guess];
15: ?>
16: <html>
17: <head>
18: <title>Listing 9.7 Saving state with a hidden field</title>
19: </head>
20: <body>
21: <h1>
22: <?php echo $message ?>
23: </h1>
24: <p><strong>Guess number:</strong> <?php echo $num_tries ?></p>
25: <form action="<?php echo $_SERVER[PHP_SELF] ?>" method="POST">
26: <p><strong>Type your guess here:</strong>
27: <input type="text" name="guess" value="<?php echo $guess ?>">
28: <input type="hidden" name="num_tries" value="<?php echo $num_tries ?>">
29: <p><input type="submit" value="submit your guess"></p>
30: </form>
31: </body>
32: </html>

The hidden field on line 28 is given the name "num_tries". We also use PHP to write its value. While we're at it, we do the same for the guess field on line 27 so that the user can always see his last guess. This technique is useful for scripts that parse user input. If we reject a form submission for some reason, we can at least allow our user to edit his previous query.

Within the main PHP code, we use a ternary operator to increment the $num_tries variable. If the $num_tries variable is set, we add one to it and reassign this incremented value; otherwise, we initialize $num_tries to 0. Within the body of the HTML, we can now report to the user how many guesses he's made.

Put these lines into a text file called listing9.7.php, and place that file 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).


/ 323