quiz-klapek/test/test.php
2025-05-29 17:52:22 +02:00

43 lines
No EOL
1.6 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 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
jsonMsg("Nieprawidłowy request");