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>