In the following PHP code, I'm trying to generate a random number if its not already and store it in a variable called $number
, also I'm taking user input and storing it in $userInput
.
Every time the submit button is pressed , the same page is called again using $_SERVER['PHP_SELF']
.
My problem is that I want the $number
to keep its value once its set. no matter how many times the submit button is pressed, which is something that is not happening now. the $number
is set every time I press submit button.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Number Guessing Game!</title>
</head>
<body>
<?php
$userInput = $_POST['number'];
if(!$number){
$number = rand(1, 500);
}
else{
echo "random number is $number <br>";
echo "you entered $userInput";
}
echo "<h3> $number </h3>"; //just to see if the number is changing everytime
?>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
<input type="text" name="number" /> <input type="submit" name="Submit"
value="Submit" />
</form>
</body>
</html>
To make your random number persist betwen page views, you'll need to use sessions
The easiest way without using cookies or sessions is just to pass the value in an hidden field in your form. When submit is pressed it will be passed across.
Use cookies/sessions if you want it to have the same value on returning to the page later on (i.e. closing the browser then reopening at a later stage). Use the form hidden field if you only want it to persist when pressing the submit button.
You'll need to implement PHP sessions. The number which you assign to $number is only accessible in the code that is called after it is set.
W3Schools PHP Session tutorial
Hopefully the link will help you.
Cheers
After php run's the script the variables are destroyed. Use cookies, seesions or sql for keeping the data over pages.