数据库中的随机数据

时间:2016-03-09 09:10:31

标签: php mysql forms random

我正在进行一个测验页面,它从表格中提问并将结果存储在另一个表格中。它工作正常。但我想从表中随机提问并存储it.ques []用于存储所有答案。请帮我这样做。 这是我的测验页面

Quiz.php

<?php   
error_reporting(E_ALL &~ E_NOTICE &~ E_DEPRECATED); 
$rs=mysql_query("select * from question where testid=$tid order by quesid ",$cn) or die(mysql_error());

if($_SESSION[qn]>mysql_num_rows($rs)-1)
{
unset($_SESSION[qn]);
echo "<h1 class=head1>Some Error  Occured</h1>";
session_destroy();
echo "Please <a href=UserHome.php> Start Again</a>";

exit;
}
        $n=0;
        while($row= mysql_fetch_row($rs)){?>
        <form name="myfm" id="myfm" method="post" action="QuizSub.php">
        <table width=100%> <tr> <td width=30><td></td></td></tr> <table border=0>
        <?php $n=$n+1; ?>
        <tr><td>Question <?php echo $n.") "; echo $row[2]; ?></td></tr>
        <tr><td class=style8>A. <input type="radio" name="ques['<?php echo $n; ?>'][]" value=1><?php echo $row[3]; ?></td></tr>
        <tr><td class=style8>B. <input type="radio" name="ques['<?php echo $n; ?>'][]" value=2><?php echo $row[4];?></td></tr>
        <tr><td class=style8>C. <input type="radio" name="ques['<?php echo $n; ?>'][]"  value=3><?php echo $row[5];?></td></tr>
        <tr><td class=style8>D. <input type="radio" name="ques['<?php echo $n; ?>'][]"  value=4><?php echo $row[6];?></td></tr>

    <?php 
        }
        echo "<tr><td><input type=submit name=submit id='result' value='Get Result'></form>";
        ?>
        </table></table>
        </form> 

回答存储页面

QuizSub.php

    <?php 
    error_reporting(E_ALL &~ E_NOTICE &~ E_DEPRECATED);
    $query="select * from question";

        $rs=mysql_query("select * from question where testid=$tid order by quesid ",$cn) or die(mysql_error());
        if($submit=='Get Result')
        { 
        $_SESSION[trueans]=0;
        $_SESSION[qn]=0;


        $ans=array();



        $questions = $_POST["ques"];
        foreach ($questions as $q) {  
        $_SESSION[qn]=$_SESSION[qn]+1;    
        $ans=$q[0][$i];
        $rw=mysql_fetch_row($rs);
        mysql_query("insert into useranswer(sessid, testid, ques, ans1,ans2,ans3,ans4,correctans,yourans) values ('".session_id()."',       $tid,'$rw[2]','$rw[3]','$rw[4]','$rw[5]', '$rw[6]','$rw[7]','$ans')") or die(mysql_error());
  ?>

我为此尝试了RAND(),但问题和答案不匹配。

 $rs=mysql_query("select * from question where testid=$tid order by RAND()",$cn)

请帮我找一个解决方案..谢谢......

1 个答案:

答案 0 :(得分:2)

将问题ID传递为(hidden),并在插入答案页面时,根据问题ID进行操作

    mysql_query("insert into useranswer(sessid, testid, ques, 
    ans1,ans2,ans3,ans4,correctans,yourans) values ('".session_id()."',
    $tid,'$rw[2]','$rw[3]','$rw[4]','$rw[5]', '$rw[6]','$rw[7]','$ans') 
    WHERE quesid = ".$rw['quesid']. ") or die(mysql_error());