2013-02-07 176 views
0

有了下面的代碼我顯示了從數據庫檢索的問題:如何以隨機順序顯示內容?

$qandaquery = "SELECT q.QuestionId, q.QuestionNo, q.QuestionContent 
        FROM Question q 
        WHERE SessionId = ? 
        GROUP BY q.QuestionId 
        ORDER BY q.QuestionId"; 

    $qandaqrystmt=$mysqli->prepare($qandaquery); 
    // You only need to call bind_param once 
    $qandaqrystmt->bind_param("i",$session); 
    // get result and assign variables (prefix with db) 
    $qandaqrystmt->execute(); 
    $qandaqrystmt->bind_result($qandaQuestionId,$qandaQuestionNo,$qandaQuestionContent); 

    $arrQuestionId = array(); 
    $arrQuestionNo = array(); 
    $arrQuestionContent = array(); 


    while ($qandaqrystmt->fetch()) { 
    $arrQuestionId[ $qandaQuestionId ] = $qandaQuestionId; 
    $arrQuestionNo[ $qandaQuestionId ] = $qandaQuestionNo; 
    $arrQuestionContent[ $qandaQuestionId ] = $qandaQuestionContent; 

    } 

    $qandaqrystmt->close(); 


foreach ($arrQuestionId as $key=>$question) { 

?> 

<div class='lt-container'> 
<p><strong>QUESTION <span id="quesnum"></span>:</strong></p> 
<p><?php echo htmlspecialchars($arrQuestionNo[$key]) . ": " . htmlspecialchars($arrQuestionContent[$key]); ?></p> 
</div> 


<?php 

} 

?> 

現在它說:QUESTION

<p><strong>QUESTION # <?php echo $q; ?> :</strong></p> <?php $q++; ?>

我想要留在同一個地方

但它顯示問題的詳細信息:

<p><?php echo htmlspecialchars($arrQuestionNo[$key]) . ": " . htmlspecialchars($arrQuestionContent[$key]); ?></p> 

我希望它以RANDOM順序顯示問題。因此,舉例來說,如果我有3個問題如下:

QUESTION 1: 

1. What is 2+2? 

QUESTION 2: 

2. What is 3+3? 

QUESTION 3: 

3. What is 4+4? 

它可以顯示的順序作爲一個例子:

QUESTION 1: 

2. What is 3+3? 

QUESTION 2: 

3. What is 4+4? 

QUESTION 3: 

1. What is 2+2? 
+0

學習如何['shuffle'](http://php.net/manual/en/function。 shuffle.php)... – Floris

回答

0

代替ORDER BY q.QuestionId使用ORDER BY RAND()

+0

只用這個方法的一個問題,我想添加一些與每個問題的複選框,這些複選框將是答案,答案是在查詢無論如何,正確和不正確的答案,如果我使用你的方法,這些複選框答案是否屬於這些問題,當他們隨機?那有意義嗎? – user2048994

+0

隨着我給你的,行將被隨機化在一起。即所有列將匹配給定的行,只是行將被洗牌 –

0

shuffle()函數隨機化數組中元素的順序。 Read more

<?php 
$my_array = array("a" => "Dog", "b" => "Cat", "c" => "Horse"); 

shuffle($my_array); 
print_r($my_array); 
?> 

rray ([0] => Cat [1] => Horse [2] => Dog) 
+0

因此,看看它,我是否需要在我的代碼中洗牌$ arrQuestionId – user2048994

0

如何MySQL的rand()函數例如

$qandaquery = "SELECT rand() as pos, q.QuestionId, q.QuestionNo, q.QuestionContent 
        FROM Question q 
        WHERE SessionId = ? 
        GROUP BY q.QuestionId 
        order by pos";