...

View Full Version : Saving state with a hidden field



theriver
01-22-2008, 02:48 AM
Hi, I am learning PHP from sams each yourself php, mysql and apache.
Need help with the following exercise, saving state with a hidden field.

It is a simple script of "number guessing machine". The problem is that the "guess number" does not increased with each guess!

The script is as follow:

<?php
$num_to_guess =42;
$num_tries = (isset($_POST[num_tries]))? $num_tries + 1: 0 ;
$message = "";
if(!isset($_POST[guess])){
$message = "welcome to the guessing game.";
}elseif ($_POST[guess] > $num_to_guess){
$message = "$_POST[guess] Wrong, it s too big.";
}elseif ($_POST[guess] < $num_to_guess){
$message = "$_POST[guess] Wrong, it is too small";
}else{
$message ="$_POST[guess] Correct guess!";

}
$guess = $_POST[guess];
?>
<html>
<head>
<title> </title>
</head>
<body>
<h1>
<?php print $message ?>
</h1>
Guess Number: <?php print $num_tries ?>
<form action="<?php print $_SERVER[PHP_SELF] ?>" method="post">
Type your guess here:
<input type="text" name="guess" value="<?php print $guess ?>">
<input type="hidden" name="num_tries" value="<?php print $num_tries ?>">
<input type="submit" value="Hit it">
</form>
</body>
</html>

abduraooft
01-22-2008, 07:51 AM
Your code is not assigning the value there

$num_tries = (isset($_POST[num_tries]))? $num_tries + 1: 0 ;
should be something

$num_tries = (isset($_POST['num_tries']))? $_POST['num_tries'] + 1: 0 ;

theriver
01-22-2008, 11:49 AM
Your code is not assigning the value there

$num_tries = (isset($_POST[num_tries]))? $num_tries + 1: 0 ;
should be something

$num_tries = (isset($_POST['num_tries']))? $_POST['num_tries'] + 1: 0 ;

Thank you, the script is working now with your help.
Could you explain a little bit the purpose of the following code

<input type="hidden" name="num_tries" value="<?php print $num_tries ?>">

Thanks again

abduraooft
01-22-2008, 12:29 PM
It simply storing the current value of trial in a hidden field to be used for the next trial.
Convince yourself by changing hidden to text
(Otherwise you may have to use a SESSION variable to keep it in memory for later use.)

theriver
01-23-2008, 02:53 AM
It simply storing the current value of trial in a hidden field to be used for the next trial.
Convince yourself by changing hidden to text
(Otherwise you may have to use a SESSION variable to keep it in memory for later use.)

Thanks again for your useful tip.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum