quiz-klapek/test/test.php
2025-05-28 23:59:39 +02:00

48 lines
No EOL
1.7 KiB
PHP

<?php
include $_SERVER["DOCUMENT_ROOT"] . "/php/scripts.php";
if (!checkLogin()) {
jsonMsg("Nie jesteś zalogowany");
exit();
}
if ($_SERVER['REQUEST_METHOD'] == "POST" && isset($_POST["testLength"])) {
if ($_POST["testLength"]>100) jsonMsg("Test nie może być dłuższy niż 100 pytań");
$conn = connectDB();
$stmt = $conn->prepare("SELECT count(*) FROM questions LIMIT 1");
$stmt->execute();
$stmt->bind_result($questionsCount);
$stmt->fetch();
$questionsIDs = [];
{$i = 0;
while ($i != $_POST["testLength"]) {
$randomNum = rand(0, $questionsCount);
if (!in_array($randomNum, $questionsIDs)) {
$questionsIDs[] = $randomNum;
$i++;
}
}}
$stmt->close();
$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ń";
header('Content-Type: application/json');
echo json_encode($result);
} else
jsonMsg("Nieprawidłowy request");