Jump to content

forms and passing variables


emmavt

Recommended Posts

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  ;D 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
Share on other sites

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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.