View Single Post

  #1 (permalink)  
Old 09-06-2004
Miffed
 
Posts: n/a
Default newbie needs help with checking for posted data

It's a bit of a cliche, but I'm an experienced programmer, I'm only new to
php (and web programming in general to be honest).

Anyway, been using "TY PHP in 24hrs" with PHP 4.3.6 without too many
problems, until I came
across the following code:

<?php
$num_to_guess = 42;
$message = "";
$num_tries = ( isset( $num_tries ) ) ? ++$num_tries : 0;
//print("numtries= " . $num_tries); // I've added this line
if ( ! isset( $_POST["guess"] ) ) {
$message = "Welcome to the guessing machine!";
}
elseif ( $_POST["guess"] > $num_to_guess ) {
$message = $_POST["guess"] . " is too big! Try a smaller number";
}
elseif ( $_POST["guess"] < $num_to_guess ) {
$message = $_POST["guess"] . " is too small! Try a larger number";
}
else { // must be equivalent
$message = "Well done!";
}
$_POST["guess"] = (int) $_POST["guess"];
?>

<html>
<head>
<title>Listing 9.11 Saving state with a hidden field</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 $_POST["guess"]?>">
<input type="hidden" name="num_tries" value="<?php print $num_tries?>">
</form>
</body>
</html>

It's just a very simple 'guess the number' game (so simple, the number is
hard-coded). The only 'interesting' thing to note is that the html form
code calls itself using PHP_SELF. The only other point of interest is that
the original code doesn't prefix PHP_SELF with $_SERVER as I have had to do
(otherwise it won't comple for me, ditto for all the references to the
'guess' variable).

The code does work EXCEPT for the 'num_tries' bit. I know from a previous
example that data isn't posted when the field is empty(or is it?) which is
why (I assume) the isset() function is used to set num_tries to zero when
nothing is received. So why doesn't this work second time around?

And before anyone says anything, yes I have just posted this in the alt.php
group, but I've only just seen a post referring to this much busier group.


Reply With Quote