1

I know my question title is not clear and I will explain here.

There is four radio buttons and its like examination test where every question have 4 answers. Problem is every question's should have random answer option.
the right answer will contain value=1.

Q1 This is question 1?

<input type ="radio" value="1" />
<input type ="radio" value="2" />
<input type ="radio" value="3" />
<input type ="radio" value="4" />

Q2 This is question 2?

 <input type ="radio" value="2" />
    <input type ="radio" value="4" />
    <input type ="radio" value="1" />
    <input type ="radio" value="3" />

How can I generate random option?

I am using PHP and fetching options value from database.

mikek3332002
  • 3,546
  • 4
  • 37
  • 47
Ahmad Sayeed
  • 344
  • 2
  • 14
  • depending on the db structure you could add `order by rand()` to each query. or randomise the data via php –  Mar 31 '16 at 04:02
  • Do you want a random option or a random order? – Harry Mar 31 '16 at 04:13
  • maybe checking out this post might help http://stackoverflow.com/questions/1533910/randomize-a-sequence-of-div-elements-with-jquery – Anthony Mar 31 '16 at 04:21

2 Answers2

3

With PHP you can create an array with all the possible values and then suffle them:

$vals = [1, 2, 3, 4];
shuffle ($vals);
for ($i = 0; $i < count ($vals); $i++) : ?>
    <input type="radio" value="<?php echo $vals[$i] ?>" />
<?php endfor ?>

Every time you want new random values you can call shuffle again.

0
select * from your_table order by rand()

E X A M P L E

Database:

TABLE: question
id question
1  what is..
2  when did..
3  Which one..

TABLE: answer
id question_id answer_options  correct
1  1           answer 1        0
2  1           answer 2        1
3  1           answer 3        0
4  1           answer 4        0

Query:

Question loop STARTS

# Use the question_id to loop through the below
$query        = "SELECT * FROM answer where question_id='$question_id' order by rand()";
$qr           = mysqli_query($con, $query);
if (mysqli_num_rows($qr) > 0)
{
$count = 2;
while ($res = mysqli_fetch_object($qr))
{
    if ($res->correct == 1)
    $value = 1;
    else
    $value = $count++;

    echo '<input type="radio" value="'.$value.'" /> '.$res->answer_options;
}
}

Question loop ENDS

Note: Didnt tested

J.K
  • 1,382
  • 1
  • 11
  • 27