View Randomize Option with Next and Back buttons
Hi,
I have a problem. In the following code I would like to randomize 5 questions out of 10 and display it one by one by clicking 'Next' button. In addition, I like to see the previous question by clicking 'Back' button.
Problem is: questions are not coming properly when I toggle between Back and Next buttons. They are providing different result in different clicking. Why this is happening ? Please help.
PHP Code:
<?php
$question=array(
0 => "Question 01",
1 => "Question 02",
2 => "Question 03",
3 => "Question 04",
4 => "Question 05",
5 => "Question 06",
6 => "Question 07",
7 => "Question 08",
8 => "Question 09",
9 => "Question 10"
);
$answer=array(
0 => "Answer 01",
1 => "Answer 02",
2 => "Answer 03",
3 => "Answer 04",
4 => "Answer 05",
5 => "Answer 06",
6 => "Answer 07",
7 => "Answer 08",
8 => "Answer 09",
9 => "Answer 10"
);
$id=array(0,1,2,3,4,5,6,7,8,9);
shuffle($id);
session_start();
$_SESSION["count"] = 0;
if(isset($_POST["back"]))
{
if($_SESSION["count"] > 0)
$_SESSION["count"] = $_SESSION["count"] - 1;
}
if(isset($_POST["next"]))
{
$_SESSION["count"] = $_SESSION["count"] + 1;
if($_SESSION["count"] > 4)
header("Location:result.php");
}
?>
<html>
<head>
<title>Test Random Question</title>
</head>
<body>
<form name="f" method="POST" action="<?php echo $_SERVER["PHP_SELF"]; ?>">
<p align="center">
<?php
echo $question[$id[$_SESSION["count"]]];
?>
</p>
<p align="center">
<input type="submit" id="back" value="Back">
<input type="submit" id="next" value="Next">
</p>
</form>
</body>
</html>
I will be waiting for the reply. Thanks a lot.
Re: View Randomize Option with Next and Back buttons
When you say not properly do you mean that you start at 6 go forwards to 9 and then back to 2?
(say)
This is because the random order is not preserved across page calls. You shuffle the order every time. You could put a list of five questions into session data
PHP Code:
$_SESSION['questionlist'] = array(1,9,5,7,3);
Then you would have some form of preservation of order...
Is that what you are after?