我有数据库表,其中包含许多问题,每个问题都有相应的答案选项(多项选择题)。
表格中的列如下所示:
questionID | questionText |回答| option1 |选项2 |选项3 | answerExplanation
在我的session.php
文件中,我使用PHP和mySQL从数据库中提取单个问题(带有答案选项),该问题保存在变量$ question中。
然后在我的$question
文件中使用此index.php
来显示问题,例如
Question: <?php echo $question['questionText'] ?>
Option 1: <?php
> echo $question['option1] ?>
Option 2: <?php echo $question['option2']?>.
我想使用SESSION存储一组用户看过的问题。
然而,我对此有些困难。似乎会话一直在重置每个新问题。
以下是我的session.php
:
<?php
session_start();
echo session_id();
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "dbname";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// initialise session variable with array
$_SESSION['questionhistory'] = [];
//Total Number of Questions in DB
$query_count = $conn->query("SELECT questionID FROM BBQuestions");
$totalquestions = $query_count->num_rows;
function findQuestion() {
global $conn;
$sql = "SELECT * FROM BBQuestions ORDER BY rand() LIMIT 1";
$result = $conn->query($sql);
$question = $result->fetch_assoc();
$q_id = $question["questionID"]; //Get ID for question
$q_id_integer = (int)$q_id; // Integer-ise the ID.
// Checks to see if question is already seen (i.e. in SESSION['questionhistory'])
if (in_array($q_id_integer, $_SESSION['questionhistory'])) {
return 0;
}
else {
return $question;
}
}
//checks to see if user has seen all questions
function checkIfAllDone() {
global $totalquestions;
$x = count($_SESSION['questionhistory']);
if ($x == $totalquestions) {
echo "ALL DONE";
return 1;
}
else {
return 0;
}
}
$done = CheckIfAllDone();
//returns a question to be is echo-ed in index.php.
function pushQuestion() {
global $done;
$question = findQuestion();
if ($done != 1) {
while ($question == 0) {
$question = findQuestion();
}
return $question;
}
}
$question = pushQuestion(); // question that is echo-ed in index.php
$question_json = json_encode($question);
$var = $question['questionID'];
array_push($_SESSION['questionhistory'], $var);
//Show whats in Array
foreach ($_SESSION['questionhistory'] as $item) {
echo $item . " - ";
}
如何确保会话数组更新时出现每个新问题?