I am building a small quiz/test engine with AJAX, PHP, and MySQL. All of the data (questions, answers, etc.) is stored in a database.
The issue that I am having is that I can't find out how to filter out the questions that have been answered by the user that is logged in, therefore resulting in questions being repeated and a never ending quiz/test.
When you click the "next question" button, an AJAX request is sent to submit_answer.php
which submits the answer (adds row to user_answers
table) and it also sends a request to get_question.php
which then returns JSON of the question information (question, answers, etc.) but I can't seem to get it to not select questions that have been answered (questions in the user_answers
table). Here is what I've got right now:
$question = mysql_query("SELECT *, q.id qid, q.question question_text
FROM questions q, user_answers ua
WHERE q.id != ua.question_id
AND ua.test_id = $test
AND ua.user_id = $_SESSION[userid]
ORDER BY rand()
LIMIT 1");
$q = mysql_fetch_assoc($question);
This query is supposed to select the questions that have the test_id
of the current test, has the user_id
as the current user, and not in the user_answers
table. But apparently, I'm just not doing it right.
You can see the entire get_question.php
file here: http://pastebin.com/Td6mqp49
Here are my table structures as requested by @MadaraUchiha:
questions
user_answers
SELECT *, q.id qid, q.question question_text
FROM questions q
WHERE NOT EXISTS (
SELECT TRUE
FROM user_answers ua
WHERE ua.question_id = q.id
AND ua.test_id = $test
AND ua.user_id = $_SESSION[userid]
)
ORDER BY rand()
LIMIT 1
The reason why your query wasn't working is that q.id != ua.question_id
will match as long as there is at least one answer that doesn't belong to the question - any answer.
You need a left outer join between the questions to the user_answers tables.
The final query looks like:
SELECT *, q.id qid, q.question question_text
FROM questions q left outer join
user_answers ua
on q.id = ua.question_id and
ua.test_id = $test and
ua.user_id = $_SESSION[userid]
WHERE ua.user_id is null
ORDER BY rand()
LIMIT 1
SELECT * FROM
questions q
WHERE
q.id NOT IN (
SELECT question_id as id
FROM user_answers
WHERE ua.test_id = $test AND ua.user_id = $_SESSION[userid]
)
On a side note, make sure you properly sanitize the data before passing to the SQL.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.