Show sourcecode
The following files exists in this folder. Click to view.
webbserverprogrammering/submissions/projekt-quiz/includes/
db_connect.php
footer.php
functions.php
header.php
session_config.php
functions.php
90 lines UTF-8 Unix (LF)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
<?php
function saveQuizToDatabase($pdo, $title, $description, $questions, $admin_id = null) {
try {
// Starta transaktion (allt eller inget sparas)
$pdo->beginTransaction();
// TABELL 1: Spara QUIZ-info
$stmt = $pdo->prepare("
INSERT INTO quizzes (title, description, created_by, created_at)
VALUES (:title, :description, :admin_id, NOW())
");
$stmt->execute([
':title' => $title,
':description' => $description,
':admin_id' => $admin_id
]);
// Hämta det ID som just skapades för quizet
$quiz_id = $pdo->lastInsertId();
// LOOP genom alla frågor - use a sequential counter for proper ordering
$question_order = 0;
foreach ($questions as $question) {
// TABELL 2: Spara FRÅGA
$stmt = $pdo->prepare("
INSERT INTO questions (quiz_id, question_text, question_order)
VALUES (:quiz_id, :text, :order)
");
$stmt->execute([
':quiz_id' => $quiz_id,
':text' => $question['text'],
':order' => $question_order
]);
// Increment order for next question
$question_order++;
// Hämta det ID som just skapades för frågan
$question_id = $pdo->lastInsertId();
// LOOP genom alla svar för denna fråga
foreach ($question['answers'] as $answer_index => $answer) {
// TABELL 3: Spara SVAR
// Kolla om detta svar är det rätta svaret
$is_correct = ($answer_index == $question['correct_answer']) ? 1 : 0;
$stmt = $pdo->prepare("
INSERT INTO answers (question_id, answer_text, is_correct, answer_order)
VALUES (:question_id, :text, :is_correct, :order)
");
$stmt->execute([
':question_id' => $question_id,
':text' => $answer['text'],
':is_correct' => $is_correct,
':order' => $answer_index
]);
}
}
// Allt gick bra! Bekräfta transaktionen
$pdo->commit();
// Omdirigera till dashboard med success-meddelande
$_SESSION['success'] = "Quiz skapad!";
header("Location: dashboard.php");
exit();
} catch (Exception $e) {
// Något gick fel - ångra ALLT
$pdo->rollBack();
// Logga felet
error_log("Quiz creation error: " . $e->getMessage());
// Visa fel till admin
$_SESSION['error'] = "Något gick fel vid skapande av quiz. Försök igen.";
return false;
}
}
?>