emmavt Posted July 12, 2007 Share Posted July 12, 2007 Hello. I am new to PHP and trying to use a PHP variable and pass it every time I call the page. The variable is $rn that should be a called randomly using rand() if the value of it is empty. However, the following code does not work. if (isset($guess)) { $rn = rand(1, 100); } The form in the page calls itself so it reloads and I am wondering how I pass this variable in the form each time and when the variable is sert to a value, not have rand() overwrite the value. Here is all my code. Thanks in advance Emma <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Untitled Document</title> </head> <body> What is your guess? <?php echo "<FORM METHOD='POST' ACTION='j_rand.php'>"; echo "<INPUT NAME='Name' TYPE='TEXT'>"; echo "<br>"; //echo "<INPUT TYPE='HIDDEN' NAME='rn' VALUE='hello'>"; echo "<br>"; echo "<INPUT TYPE='SUBMIT' VALUE='SUBMIT'>"; echo "</FORM>"; if (isset($rn)) { $rn = rand(1, 100); } echo "This is the random number " . $rn . "<br>"; $guess = $_POST['Name']; echo "This is the guess ", $guess, "<br>"; if ($guess == $rn) { echo "<br>Correct!"; } elseif ($guess > $rn) { echo "<br>To high. Guess again."; } elseif ($guess < $rn && $guess > 0) { echo "<br>To low. Guess again."; } elseif (isset($guess)) { echo 'Please enter a guess'; } else { echo "<br>You broke it!"; } ?> </body> </html> Link to comment https://forums.phpfreaks.com/topic/59718-forms-and-passing-variables/ Share on other sites More sharing options...
GingerRobot Posted July 12, 2007 Share Posted July 12, 2007 I think you just need to get the variables from the $_POST array at the top of your script: <?php $rn = $_POST['rn']; $guess = $_POST['guess']; //the rest of your script Also, for future reference, put your code in tags(without the spaces) - makes it a whole stack easier to read. Link to comment https://forums.phpfreaks.com/topic/59718-forms-and-passing-variables/#findComment-296798 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.