Reputation: 111
As the title says I want to execute second function after first function is executed. In other words, if user clicks 'Draw First number' button, a random number from 1-10 will be displayed along with a 'Draw Second number' button and then if user clicks 'Draw Second number' button, another random number from 1-10 will be displayed.
I have tried the following code but when I click 'Draw Second Number' button, it returns me to the start of the process.
<?php
if (isset($_POST['firstnumber'])) {
function roll () {
return mt_rand(1,10);
}
echo 'First Number: '.roll().'<form method="post"><input type="submit" value="Draw second number" name="secondnumber"></form>';
if (isset($_POST['secondnumber'])) {
echo 'Second Number: '.roll();
}
}
?>
<form method="post">
<input type="submit" value="Draw first number" name="firstnumber">
</form>
I expect code to display second number when 'Second Number' button is clicked rather than going to initial code.
Upvotes: 1
Views: 206
Reputation:
At the start of your file you check the following condition
<?php if (isset($_POST['firstnumber'])) {
So everything inside this if statement will only execute if the statements evaluates true.
If you are submitting your hardcoded HTML Formular (the "firstnumber" one). The If statement evaluates true, thus the code inside it gets run.
Inside the If Statement you call your previously defined function roll();
and you echo out another formular.
This formular (the "secondnumber" one) is only echo'd out if the above if statement is evaluated true.
If you now submit your second formular (the "secondnumber" one) the if statement at the top evaluates false, because then the field firstnumber
in $_POST is not set!
Why isn't it set? Because you just submitted a formular (the "secondnumber" one) which doesn't have any field named firstnumber
.
Try the following code:
<?php
function roll() {
return mt_rand(1,10);
}
if (isset($_POST['firstnumber']) === true || isset($_POST['secondnumber']) === true) {
if (isset($_POST['firstnumber'])) {
echo 'First Number: ' . roll() . '<form method="post"><input type="submit" value="Draw second number" name="secondnumber"></form>';
}
if (isset($_POST['secondnumber'])) {
$secondNumber = roll();
}
}
?>
<form method="post">
<input type="submit" value="Draw first number" name="firstnumber">
</form>
Upvotes: 1