quiz-klapek/test/test.php
2025-05-31 17:39:35 +02:00

62 lines
No EOL
2.5 KiB
PHP

<?php
include $_SERVER["DOCUMENT_ROOT"] . "/php/scripts.php";
if (!checkLogin()) {
jsonMsg("Nie jesteś zalogowany");
exit();
}
if ($_SERVER['REQUEST_METHOD'] == "POST" && isset($_POST["testStart"])) {
if ($_POST["testLength"] > 100)
jsonMsg("Test nie może być dłuższy niż 100 pytań");
$conn = connectDB();
$stmt = $conn->prepare("SELECT QID FROM questions");
$stmt->execute();
$stmt->bind_result($QID);
$allQIDs = [];
while ($stmt->fetch())
$allQIDs[] = $QID;
$stmt->close();
shuffle($allQIDs);
$questionsIDs = array_slice($allQIDs, 0, $_POST["testLength"]);
$filler = implode(",", array_fill(0, count($questionsIDs), "?"));
$stmt = $conn->prepare("SELECT QID, content, answerA, answerB, answerC, answerD FROM questions WHERE QID IN ($filler) ORDER BY FIELD(QID, $filler)");
$types = str_repeat("i", count($questionsIDs) * 2);
$arrMerged = array_merge($questionsIDs, $questionsIDs);
$stmt->bind_param($types, ...$arrMerged);
$stmt->execute();
$stmt->bind_result($QID, $content, $answerA, $answerB, $answerC, $answerD);
$result = [];
while ($stmt->fetch())
$result["questions"][] = [
"QID" => $QID,
"content" => $content,
"answerA" => $answerA,
"answerB" => $answerB,
"answerC" => $answerC,
"answerD" => $answerD
];
$stmt->close();
$conn->close();
$result["msg"] = "Wygenerowano " . count($result["questions"]) . " pytań";
echo json_encode($result);
} else if ($_SERVER['REQUEST_METHOD'] == "POST" && isset($_POST["testEnd"])) {
$allTestAnswers = [];
$answersQIDs = [];
foreach ($_POST as $key => $value) {
if (in_array($key, ["save", "rank", "testEnd", "testLenght"]) || !is_numeric($key)) continue;
$allTestAnswers[(int)$key] = ["ans" => $value, "pos" => $_POST["q$key"], "cor" => false];
$answersQIDs[] = (int)$key;
}
$conn = connectDB();
$filler = implode(",", array_fill(0, count($allTestAnswers), "?"));
$stmt = $conn->prepare("SELECT QID, answerChar FROM questions WHERE QID IN ($filler)");
$types = str_repeat("i", count($allTestAnswers));
$stmt->bind_param($types, ...$answersQIDs);
$stmt->execute();
$stmt->bind_result($QID, $answerChar);
while ($stmt->fetch()) if ($answerChar==$allTestAnswers[$QID]["ans"]) $allTestAnswers[$QID]["cor"] = true;
$stmt->close();
$conn->close();
echo json_encode($allTestAnswers);
} else
jsonMsg("Nieprawidłowy request");