使用php和mysql获取随机id

时间:2013-08-01 16:55:05

标签: php javascript mysql

我有2个包含的表 id,subject,exam,qution,qution_id,在表1中 在表2中 ID,question_id,答案,是正确的,  在这里我有一个问题,从数据库中获取随机问题 我正在使用

$singleSQL = mysql_query("SELECT * FROM questions WHERE id='$question'  LIMIT 1");
    while($row = mysql_fetch_array($singleSQL)){
        $id = $row['id'];
        $thisQuestion = $row['question'];
        $type = $row['type'];
        $subject =$row['subject'];
        $exam =$row['exam'];
        $explan =$row['explan'];
        $question_id = $row['question_id'];
        $s ='<strong>'.$subject.'</strong>';
        $e ='<small>'.$exam.'</small>';
        $q = '<h2>'.$thisQuestion.'</h2>';
        $ex ='<p class="exp">'.$explan.'</p>';
        $sql2 = mysql_query("SELECT * FROM answers WHERE question_id='$question' ORDER BY rand()");
        while($row2 = mysql_fetch_array($sql2)){
            $answer = $row2['answer'];
            $correct = $row2['correct'];
            $answers .= '<table class="table table-hover table-bordered"> <tr>
            <td><label style="cursor:pointer;"><input type="radio" name="rads" value="'.$correct.'">'.$answer.'</label></td>
            </tr></table>
            <input type="hidden" id="qid" value="'.$id.'" name="qid"><br />
            ';

        }
        $output = ''.$s.','.$e.''.$q.','.$answers.''.$ex.' <span id="btnSpan"><button onclick="post_answer()" id="show">Submit</button></span>';
        echo $output;
       }
    }

当我点击提交答案时,我应该随机得到下一个问题 喜欢

 index.php?question=

我应该在这里使用什么 当页面加载时,应从数据库中获取随机问题 PLZ帮助我需要这个 提前谢谢

2 个答案:

答案 0 :(得分:1)

$randomparameter = mysql_query("SELECT MIN(id) as min_id,MAX(id) as max_id FROM questions ");
$row = mysql_fetch_array($randomparameter );
$random_questin_id=rand($row['min_id'],$row['min_id']);

答案 1 :(得分:0)

也许您可以使用数组存储问题ID,并使用php的rand函数生成一个随机数(介于0和列表大小之间),这将是问题ID列表的索引。

int rand ( int $min , int $max )