简体   繁体   中英

to get random id using php and mysql

I have a 2 tables which contain id,subject,exam,qution,qution_id, in table 1 in table 2 id,question_id,answer,correct, here i have a problem to get a random questions from data base i am using

$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;
       }
    }

when i click submit answer i should get a next question randomly like

 index.php?question=

what should i use here when ever a page loads it should get a random question from database plz help iam in need of this thanx in advance

$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']);

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

int rand ( int $min , int $max )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM