我正在尝试从特定于测验的数据库中获取数据。我有两个名为“问题”和“选项”的表。每个问题都有 2 个相应的选项,“questionID”行作为外键出现在“options”表中。 我使用此查询获取 4 个随机问题及其相应的答案:
SELECT * FROM questions INNER JOIN options ON
questions.questionID=options.questionID, (SELECT questionID AS sid FROM questions
ORDER BY RAND( ) LIMIT 4 ) tmp WHERE questions.questionID = tmp.sid AND
options.questionID=questions.questionID ORDER BY questions.questionID
这个查询运行良好,并从 phpMyAdmin 上的问题和选项表中检索适当的行,但是当我在 php 中获取数组,然后使用 AJAX 检索数组时,所有选项都是随机的,并且与他们的问题不匹配 - 其中一些选项确实如此与所选的任何问题都不匹配。 预先感谢您的任何建议。
我自己检查了 php 字段,看来这只是 AJAX 的错误。现在我明白为什么了 - 我对文件进行了两次调用,我认为它可能会再次运行查询,这就是答案不匹配的原因。有什么解决办法吗?
这是我的 AJAX 调用,同样适用于具有不同 url 参数的答案:
var dataQuest = (function() {
var questions;
function load(){
$.ajax({
type: "GET",
url: "randomQ.php?q=0",
dataType: 'json',
async: false,
success: function(data){
questions = data;
//alert(questions);
alert(questions);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
$('#place1').text("Error: " +textStatus +" "+ errorThrown);
}
});//end ajax
} //end of load
return {
load: function() {
if(questions) return;
load();
},
getQuest: function(){
if(!questions) load();
return questions;
}
}
})();//end of dataQuest function
根据要求 - php 位:
while( $row = $stmt->fetch()) {
$quests[] = $row['question'];
$answers[] = $row['option'];
}
//$questions = array_unique($quests);
//$answs = array_chunk($answers, 2);
if($_GET['q']==0)
{
echo json_encode($quests);
}
else
{
echo json_encode($answers);
}
我已将其更改为:
$arrays[] = $quests;
$arrays[] = $answers;
echo json_encode($arrays);
//echo json_encode($answers);
这会向 AJAX 返回适当的答案和问题 - 但是为了实现这一点 - 我需要在 Javascript 中分割这个 2D 数组 - 对于如何实现这一点的任何建议表示赞赏。
最佳答案
试试这个...
SELECT * FROM questions
LEFT JOIN options ON
questions.questionID=options.questionID
WHERE options.questionID=questions.questionID
ORDER BY RAND()
LIMIT 8 //You will need 8 rows as each question has 2 option rows
如果不查看您的数据库架构,很难知道,但这应该可行。
在您的 PHP 脚本中,此更改可能会帮助您关联 jQuery 中的数据:
while( $row = $stmt->fetch()) {
///use the PK of the question instead of arbitrary index
$quests[$row['question_id']] = $row['question'];
$answers[$row['question_id']] = $row['option'];
}
或者也许..
while( $row = $stmt->fetch()) {
//create a single array indexed by question pk with sub array of options
$quests[$row['question_id']]['question'] = $row['question'];
$quests[$row['question_id']]['options'][] = $row['option'];
}
关于php - 使用 MySQL 获取数据库记录 - 使用 PDO 进行随机行选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30750915/