mercredi 15 mars 2017

Selecting random rows from SQL database and storing for re-use on another page

My problem is, in question.php I wish to select 5 random rows from my database (questions) and then echo these questions as necessary with the associated answers. I then wish to, on result.php use those same 5 random selections in order to give correct/incorrect answer feedback. My problem is if I query the database using the same rand query I will get 5 different random questions. The query I have in question.php is:

<?php
    $query="SELECT * FROM (SELECT * FROM dspstuff ORDER BY rand() LIMIT 5) T1 ORDER BY id";
?>

I then echo the relative 4 options associated with the question in the database:

<?php       


    while($row = mysql_fetch_assoc($result)) {                                                                  
    $options = array($row['option1'], $row['option2'], $row['option3'], $row['answer']);                            
    shuffle($options);  


    echo '<p>';                                                                                         
    echo $row['id'] . '.  '; 
    echo $row['question'];
    echo '</p>';

    foreach($options as $option){?>
    <p><input type="radio" name="ID<?php echo $row['id']; ?>" value="<?php echo $option; ?>"><?php echo $option; ?></p>
    <?php  }
        echo '<br>';                              
        }                           
    ?>                                      

This all works correctly with the db connect info saved elsewhere. I need to know what query to use or possibly utilise session variables to save the random ids selected. Say I say select rows 1,2,3,4,5 from the db I need to use those rows in results.php, how would I go about achieving this?




Aucun commentaire:

Enregistrer un commentaire