通过在数据库中创建您的测验来存储带有基本表格的答案,例如:
| question |
|============|
| id (PK) |
| no |
| image_path |
| choice |
|=============|
| id (PK) |
| question_id |
| value |
| answer |
|=====================|
| user_id (PK, FK) |
| question_id (PK, FK)|
| choice_id (PK, FK) |
| user |
|=====================|
| id (PK) |
| session_id or email |
使用这样的模式,您可以轻松地使用键no
以连贯的顺序或RAND()
随机顺序呈现问题。该选项是可选的,但如果您想扩展您的测验,您可以使用它来扩展选项。
为给定用户查找下一个问题可能类似于
SELECT *
FROM question as q
JOIN answer as a
ON q.id = a.question_id
WHERE q.id NOT IN (SELECT question_id FROM answer WHERE user_id = :user_id)
AND a.user_id = :user_id
ORDER BY q.no -- or ORDER BY RAND()
LIMIT 1;
这样,您将得到用户尚未回答的第一个问题。除此之外,您要保留多少有关用户的信息取决于您。
编辑(从第一条评论添加)
您将需要在控制器中执行 2 个操作,一个用于获取要显示的内容并将 id 发送到视图,另一个用于从用户那里获取数据并将其存储到数据库中。
在您的模型中,您将需要 2 种方法(至少),一种用于获取下一个问题,另一种用于保存答案。我不知道代码点火器的细节,但这里是主要行:
Controller:
displayAction()
get user id from user model (through session variable or session id)
If you don't have a reference for the user, you need to create one and return it
get next question from question model (user id as param)
send the question data to the view
saveAction()
get user id (through session variable or session id)
get question id (from get or post param)
if you use a database to store choices, validate that the choice is possible, based on the current question
send user id, question id and the choice made to the answer model for storage
redirect to displayAction()