This Question is a bit long and I have edited too much to reduce my code but I hope anyone can help me out please!
I'm working on a Math test in times table project with php which will ask the user to enter his name and then ask him 10 questions like "2 x 2 = ?" giving four buttons to choose an answer and then after answering 10 questions the user will be redirected to result.php
page which will show the result and here is what I wrote so far in homePage.php
:
<?php
session_start();
if (isset($_POST['submit']) ) {
$_SESSION['QuestionNumber'] = 1;
$_SESSION['CorrectAnswers'] = 0;
$_SESSION['QuestionsAsnwered'] = 0;
$_SESSION['QuestionsAnswered'] = 0;
header("location: MathTest.php");
}
?>
<!DOCTYPE html>
<html>
<body>
<h1 align="center">Math Test</h1>
<form method="POST" action="">
<div style="text-align: center;">
<input type="submit" name="submit" value="Begin Test"">
</div>
</form>
</body>
</html>
and in MathTest.php which contains the problem:
<?php
session_start();
//just controlling user answer no problem here
if (isset($_POST[$_SESSION['UserAnswer']])) {
if ($_SESSION['QuestionNumber'] == 10) {
header("location: result.php");
}
if ($_SESSION['UserAnswer'] == $_SESSION['CorrectAnswer']) {
$_SESSION['QuestionNumber'] += 1;
$_SESSION['CorrectAnswers'] += 1;
$_SESSION['QuestionsAnswered'] += 1;
QuestionGenerator();
} else {
$_SESSION['QuestionNumber'] += 1;
$_SESSION['QuestionsAnswered'] += 1;
QuestionGenerator();
}
}
//I think that my problem(written down) is here
function QuestionGenerator(){
$rnd1 = rand(1, 12);
$rnd2 = rand(2, 12);
$CorrectAnswer = $rnd1 * $rnd2;
$WrongAnswer1 = $CorrectAnswer - 2;
$WrongAnswer2 = $CorrectAnswer + 2;
$WrongAnswer3 = $CorrectAnswer + 4;
$_SESSION['rnd1'] = $rnd1;
$_SESSION['rnd2'] = $rnd2;
$_SESSION['CorrectAnswer'] = $CorrectAnswer;
$_SESSION['WrongAnswer1'] = $WrongAnswer1;
$_SESSION['WrongAnswer2'] = $WrongAnswer2;
$_SESSION['WrongAnswer3'] = $WrongAnswer3;
$_SESSION['AnswersArray'] = array($_SESSION['CorrectAnswer'], $_SESSION['WrongAnswer1'], $_SESSION['WrongAnswer2'], $_SESSION['WrongAnswer3']);
}
function EchoAnswers($array) {
shuffle($array);
echo "<form method='POST' action='' ";
foreach ($array as $_SESSION['UserAnswer']) {
echo "<button><input style='width: 200px; height: 100px; font-size: 75px;' type='submit' name='" . $_SESSION['UserAnswer'] . "' value='" . $_SESSION['UserAnswer'] . "' ></button";
}
echo "</form>";
}
?>
<!DOCTYPE html>
<html>
<body>
<?php echo "<h1 align='center' style='font-size: 75px;'>Question " . $_SESSION['QuestionNumber'] . " of 10</h1>"; ?>
<h2 align="center" style="font-size: 60px"><?php echo $_SESSION['rnd1'] . " X " . $_SESSION['rnd2'] . " = ?" ?></h2>
<div align="center">
<?php EchoAnswers($_SESSION['AnswersArray']) ?>
</div>
</body>
</html>
the problem is when I click on any button it will only shuffle the answers but if I press the last button it will work full functionally
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…