2013-03-02 83 views
1

我是php的新手。我正在创建小型在线考试应用程序。我在MySql中创建了一个问题表,并希望在页面上只显示一个问题。提交该问题的答案后,在页面上显示另一个问题。任何人都可以帮助我,我该怎么做?由于从数据库中获取随机数据

回答

0

编辑2 这里是伪代码更新来解决与原代码的一些问题。

基本上这里的变化是从数据库中获取所有问题ID,然后洗牌。这可以避免自动递增序列中丢失ID的情况,这很可能。

旧代码的另一个变化是从数据库中抓取所有选定的问题,而不是一次一个。不知道我在那里想什么。

下面是一些伪代码:

// Get all questions ids. This should be fine since there shouldn't be too many cases where you will have more than 1000 questions. 
$questionIds = db.selectIdsFromQuestionsWhereTypeIsSports(); 

// Shuffle array so the question ids are out of order 
shuffle($questionIds); 

// Number of questions you want 
$quizLength = 5; 

// select your questions  
$selectedQuestions = array_slice($questionIds, 0, $quizLength); 

// Now fetch all data for selected questions 
$quiz = db.fetchByWhereIdIn($selectedQuestions); 

// Now do whatever with your question 

**原始 我不会使用MySQL rand功能。如果你有很多行,它不会提供很好的性能。此外,您还有机会再次选择相同的问题。

所以我会做的是从数据库中检索你的问题集,然后在php中洗牌。

如果您有成千上万的问题,那么我会建议随机生成一个与您的自动增量ID相关的数字序列。如果你没有使用自动增量ID,那么这将不起作用。

因此,如果您想要询问10个问题,并在数据库中有100个问题,则例如在1和100之间生成10个数字。

这种方法的一个缺点是如果你的自动增量序列有漏洞。如果你没有太多的数字,你可以把它扔出去,随机挑选另一个数字。

下面是一些伪代码:作为逗号seprated

$_SESSION['asked_question_ids'] = $asked_question_ids; 

获得其尚未使用的问题ID从会议提出的随机问题会议

// Get a count of your questions from the database 
$totalQuestions = db.count(); 

// Generate an array sequence/range 
$questionIds = range(1, $totalQuestions); 

// Shuffle array so the numbers are out of order 
shuffle($questionIds); 

// Store your questions  
$quiz = array(); 

// Number of questions you want 
$quizLength = 5; 

// Now you can retrieve questions like so 
while (count($quiz) == $quizLength) { 
    $question = db.fetchById(array_pop($questionIds); 
    if ($question != null) { 
     $quiz[] = $question; 
    } 
} 
// Now do whatever with your question 
0

组提出的问题ID

$asked_question_ids = '3, 4, 5, asked queston ids from session' 

SELECT * FROM questions WHERE qid NOT IN ($asked_question_ids) ORDER BY RAND() LIMIT 1