I'm learning php, and I'm having a hard time finding answers to this. How do I keep a variable after I've submitted a form that has to call the page again? (Weird wording?) I am trying to keep $num_to_guess and $num_tries. I'm following instructions I found to include $num_tries as a hidden input in the html block, but it still does not increment it after I submit the form.
How do I save $num_to_guess AND $num_tries after submission?
<?php
if ( !isset ( $num_tries ) )
{
$num_to_guess = rand(1, 100);
}
$num_tries = ( isset ( $_POST['num_tries'] ) ) ? $num_tries + 1 : 0;
if ( !isset ( $_POST['guess'] ) ) {
$message = "Welcome to the guessing machine!";
} elseif ( !is_numeric ( $_POST['guess'] ) ) {
$message = "I don't understand that response...";
} elseif ( $_POST['guess'] == $num_to_guess ) {
$message = "Well done! That is the number!";
} elseif ( $_POST['guess'] < $num_to_guess ) {
$message = $_POST['guess'] . " is too small!";
} elseif ( $_POST['guess'] > $num_to_guess ) {
$message = $_POST['guess'] . " is too big!";
} else {
$message = "I am terribly confused...";
}
?>
<!DOCTYPE html>
<html>
<head>
<title>A PHP Number Guessing Script</title>
</head>
<body>
<h2>The Guessing Game</h2>
<p>1-100<br/>
Guess number: <?php echo $num_tries ?></p>
<h3><?php echo $message; echo $num_to_guess?></h3>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<p><label for="guess">Type your guess here:</label><br/>
<input type="text" id="guess" name="guess" /></p>
<input type="hidden" name="num_tries" value="<?php echo $num_tries; ?>"/>
<button type="submit" name="submit" value="submit">Submit</button>
</form>
</body>
</html>
You will want to set these to a session variable like this
session_start();
$_SESSION['guess'] = $num_to_guess;
$_SESSION['tries'] = $num_tries;
Then to access them you would do...
session_start();
$guess = $_SESSION['guess'];
$tries = $_SESSION['tries'];
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments