1

我是 php 新手。我正在创建小型在线考试应用程序。我在 MySql 中创建了一个问题表,并希望在页面上只显示一个问题。提交该问题的答案后,在页面上显示另一个问题。谁能帮助我我该怎么做?谢谢

4

3 回答 3

0

将会话中的问题 ID 设置为逗号分隔

$_SESSION['asked_question_ids'] = $asked_question_ids;

使用会话中的问题 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
于 2013-03-02T06:56:00.847 回答
0

SELECT * FROM questions ORDER BY RAND() LIMIT 4

于 2013-03-02T06:43:29.053 回答
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

**原来我不会使用 MySQLrand功能。如果您有很多行,它不会提供出色的性能。此外,您面临再次选择相同问题的机会。

所以我要做的是从数据库中检索你的一组问题,然后在 php.ini 中随机播放。

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

因此,如果您想问 10 个问题,并且在您的数据库中有 100 个问题,那么例如生成 10 个介于 1 和 100 之间的数字。

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

这是一些伪代码:

// 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
于 2013-03-02T06:48:24.520 回答