Web Hosting Talk







View Full Version : PHP begginner (forms question)


RenderStream
02-12-2004, 02:48 PM
Hi, currently im working on an easy php script (guess the number game)

What i have done is:

using 2 pages:

(first page)

Generate Random number (1-10)
Get a guess from user (using html forms)

Then when they hit submit, it will transfer them to the next page, which will basically tell them if they are too big, too small, or correct etc.

Problem is, If the number is not right, it will say "too small" and will stay their (making the user hit "back" in order to try again.

----

What are the ways to overcome this? What i want to know is... Is their anyway, i can do this using only 1 html/php page ?

Thanks!

Intrigue
02-12-2004, 03:10 PM
<html>
<body>
<?
if (!strcmp($_POST["action"], "guess"))
{
$num = rand(0, 100);

if ($_POST["unum"] < $num)
{
echo "Guess is lower";
}
elseif ($_POST["unum"] > $num)
{
echo "Guess is higher";
}
else
{
echo "Good Guess!";
}
}
?>
<form action="<?= $_SERVER["PHP_SELF"] ?>" method="post">
<input name="action" type="hidden" value="guess">
<input name="unum" type="text" value="<?= $_POST["unum"] ?>"><BR>
<input type="submit" value="guess">
</form>
</body>
</html>


that should do it, hard to edit it in this textarea so it might be slightly off (syntax, perhaps forgot a ; or something).

RenderStream
02-12-2004, 03:25 PM
can u explain what these mean/do:

if (!strcmp($_POST["action"], "guess"))

and

$_SERVER["PHP_SELF"]

and

"unum"

thanks!

Rich2k
02-12-2004, 05:30 PM
unum is the name of the text field that the user makes their guess in. e.g.

<input type="text" name="unum" />

$_SERVER['PHP_SELF'] is the the script file the form is called from e.g. if you called http://www.domain.com/directory/file.php then $_SERVER['PHP_SELF'] is /directory/file.php. This is a simple way to let a form post to itself.

strcmp() is a binary safe string comparison. (see http://uk.php.net/strcmp). Personally I've never used that function, but it is just another way to compare values.

RenderStream
02-12-2004, 05:39 PM
so could i use:

if ($_POST["action"]=="guess")

?

Intrigue
02-12-2004, 06:01 PM
I was working on that example, and you dissappeared offa msn, so here's a url to it.

The form itself:
http://www.phpmonkey.org/~brandon/num.php

The Form's SRc:
http://www.phpmonkey.org/~brandon/num.php?cmd=src

That should work alot better.

bety
02-16-2004, 09:53 AM
You can also submit to the same page by omitting the 'action' property of the <form> tag. This way the page will submit to itself, instead of the URL/file stated in the 'action' parameter.