Ahmad Sayeed
Ahmad Sayeed

Reputation: 354

How to generate random radio button positions?

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.

Upvotes: 1

Views: 1056

Answers (2)

J.K
J.K

Reputation: 1374

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

Upvotes: 0

user3645103
user3645103

Reputation:

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.

Upvotes: 3

Related Questions