-1
我一直致力於製作測驗應用程序,並且我被困在一個點上。我使用PHP和MySQL來製作它。 所以,我現在想要從數據庫隨機抽取問題。但是,當我嘗試使用帶問題的rand()時,它的選擇與它應該是不同的。 我應該怎麼做同步問題的隨機性與答案。如何用數據庫中的相應答案對問題進行隨機化
class Quiz {
protected $_db;
protected $_answers = array();
protected $_questions = array();
protected $_question;
protected $_users;
protected $_leaderboard;
protected $_currentuser;
public $session;
public function __construct(\Pimple $container)
{
$this->_currentuser = $container['user'];
$this->session = $container['session'];
$this->_leaderboard = $container['leaderboard'];
$this->_users = $this->_leaderboard->getMembers();
try
{
//$this->_db = new PDO('mysql:host='.Config::$dbhost.';dbname='.Config::$dbname, Config::$dbuser, Config::$dbpassword);
$this->_db = $container['db'];
$this->_populateQuestions();
}
catch (\PDOException $e)
{
return $e;
}
}
public function getAnswers($questionid = false)
{
if ($questionid)
{
//pull answers from db for only this question
$answersql = "SELECT text FROM answers where question_id = :id ORDER BY correct DESC";
$stmt = $this->_db->prepare($answersql);
$stmt->bindParam(':id', $questionid, \PDO::PARAM_INT);
$stmt->execute();
while ($result = $stmt->fetchObject())
{
array_push($this->_answers,$result->text);
}
}
else
{
//pull all answers from db grouped by question
$answersql = "SELECT group_concat(a.text ORDER BY a.correct DESC SEPARATOR '~') FROM answers a GROUP BY a.question_id";
$stmt = $this->_db->query($answersql);
$stmt->execute();
$resultset = $stmt->fetchAll(\PDO::FETCH_NUM);
foreach ($resultset as $csv)
{
$tmparray = explode('~', $csv[0]);
array_push($this->_answers,$tmparray);
}
}
return $this->_answers;
}
public function getQuestion($questionid)
{
$questionsql = "select text from questions where id = :id order by rand()";
$stmt = $this->_db->prepare($questionsql);
$stmt->bindParam(':id', $questionid, \PDO::PARAM_INT);
$stmt->execute();
$row = $stmt->fetchObject();
$this->_question = $row->text;
return $this->_question;
}
public function getQuestions()
{
return $this->_questions;
}
private function _populateQuestions()
{
$questionsql = "select text from questions order by id asc";
$stmt = $this->_db->query($questionsql);
$stmt->execute();
while ($row = $stmt->fetchObject())
{
$this->_questions[] .= $row->text;
}
}
'從問題中選擇文本,其中id =:id order by rand()'應該只檢索具有正在傳遞的'id'的問題。你確定他們不是正確的問題嗎? – 2015-02-08 19:27:42
你是什麼意思?你能詳細說明嗎? – 2015-02-08 19:33:03