Webbserverprogrammering 1

Show sourcecode

The following files exists in this folder. Click to view.

Webserver1/Ovningar/Quiz/

account.php
create_quiz.js
create_quiz.php
fetch_table.php
frontpage.php
header.php
login.php
quiz.php
quiz_answer_finished.php
quiz_creation_finished.php
signup.php
style.css

quiz.php

216 lines UTF-8 Windows (CRLF)
<?php
session_start
();

$DEBUG false;

// Användare måste vara inloggad, annars får man inte göra quizzet
$quiz_id = isset($_GET['quiz_id']) ? $_GET['quiz_id'] : null;

if (!isset(
$_SESSION) && ["isLoggedIn"] != true) {
  
$_SESSION["lastVisited"] = "https://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
  
header("Location:login.php?redirect=true");
}

include(
"../../incl/dbconnection.php");
/**
 * @var PDO $dbconn
 */


$quiz = [];
unset(
$_POST);
?>

<!DOCTYPE html>
<html lang="sv">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Ett riktigt roligt quiz!</title>
  <link rel="stylesheet" href="style.css">
</head>

<body>
  <?php
  
if ($quiz_id) {
    
$sqlGetQuestions "SELECT *
    FROM quiz_questions
    WHERE quiz_id = ?
    ORDER BY question_order"
;

    
$sqlGetOptions "SELECT *
    FROM quiz_options
    WHERE question_id = ?"
;

    
$sqlGetQuizName "SELECT quiz_name
    FROM quiz_quizzes
    WHERE quiz_id = ?"
;

    
$quizNameStmt $dbconn->prepare($sqlGetQuizName);
    
$quizNameStmt->execute([$quiz_id]);
    
$quizName $quizNameStmt->fetch(PDO::FETCH_ASSOC)['quiz_name'];

    
$questionStmt $dbconn->prepare($sqlGetQuestions);
    
$optionStmt $dbconn->prepare($sqlGetOptions);

    
$questionStmt->execute([$quiz_id]);
    
$qStmtResult $questionStmt->fetchAll(PDO::FETCH_ASSOC);

    
$quiz['quizName'] = $quizName;
    
$quiz['questions'] = [];
    
# Parse db data
    
foreach ($qStmtResult as $questionNr => $question) {
      
$question_id $question['question_id'];
      
$optionStmt->execute([$question_id]);

      
$quiz["questions"][$questionNr] = [];
      
$quiz["questions"][$questionNr]["text"] = $question["question_text"];
      
$quiz["questions"][$questionNr]["choices"] = [];
      foreach (
$optionStmt->fetchAll(PDO::FETCH_ASSOC) as $option) {
        
$quiz["questions"][$questionNr]["choices"][] = ["text" => $option['option_text'], "correct" => $option['is_correct']];
      }
    }
    if (
$DEBUG) {
      echo 
"<pre>";
      
print_r($quiz);
      echo 
"</pre>";
    }
  
?>
    <form action="quiz_answer_finished.php" method="post" id="quiz-questions-container">
      <input type="hidden" name="quiz_id" value="<?php echo $quiz_id?>">
      <h1 class="text-center">Quiz: <?php echo $quizName?></h1>
      <div id="quiz-wrapper">
        <?php
        
foreach ($quiz["questions"] as $questionNr => $questionData):
          
$questionText $questionData["text"];
        
?>
          <div class="question-card<?php
                                    
if ($questionNr == 0) {
                                      echo 
" active";
                                    } else {
                                      echo 
" hidden";
                                    } 
?>"
            id="q<?php echo $questionNr 1?>">
            <div class="title">
              <h1 class="text-center"><?php echo $questionText?></h1>
            </div>
            <div class="question-choice-container">
              <?php
              
foreach ($questionData["choices"] as $choiceNr => $choice):
              
?>
                <label for="q<?php echo $questionNr "c" $choiceNr 1?>"><?php echo $choice["text"]; ?></label>
                <input type="radio" class="question-choice"
                  name="q<?php echo $questionNr "c" $choiceNr 1?>"
                  id="q<?php echo $questionNr "c" $choiceNr 1?>"
                  value="<?php echo $choice["text"]; ?>">
              <?php
              
endforeach
              
?>
            </div>
          </div>
            <?php
        
endforeach;
            } else {
        echo 
"<p>Invalid quiz_id!</p>";
            }
            
?>
            <div class="row">
        <button id="prevQuestionBtn" disabled>Förra frågan</button>
        <div id="progress-bar">
          <?php foreach ($quiz['questions'] as $_): ?>
            <div class="progressbar-circle"></div>
          <?php endforeach; ?>
        </div>
        <button id="nextQuestionBtn">Nästa fråga</button>
            </div>
      </div>
    <div id="finish-quiz" class="hidden">
      <h2>Slut på frågor!</h2>
      <input type="submit" value="Klicka här för att skicka in!">
    </div>
    </form>

    <div class="center-container">
      <a href="frontpage.php" style="text-decoration: none;">
        <button class="big-button">Tillbaks till startsida</button>
      </a>
    </div>

    <script>
      const nextQuestionBtn = document.getElementById("nextQuestionBtn");
      const prevQuestionBtn = document.getElementById("prevQuestionBtn");
      const progressBar = document.getElementById("progress-bar");
      const totalQuestions = document.querySelectorAll(".question-card").length;
      const finishQuizDiv = document.getElementById("finish-quiz");
      const quizWrapper = document.getElementById("quiz-wrapper");

      function gotoNextQuestion() {
        const q = document.getElementsByClassName("question-card active")[0];
        const qNr = Number(q.id.slice(1));
        const nextQuestionCard = document.getElementById(`q${qNr + 1}`);
        if (!nextQuestionCard) {
          finishQuizDiv.classList.remove("hidden")
          quizWrapper.classList.add("hidden")
          return;
        };
        nextQuestionCard.classList.remove("hidden");
        nextQuestionCard.classList.add("active")
        q.classList.remove("active");
        q.classList.add("hidden");
        if (qNr + 1 == totalQuestions) {
          nextQuestionBtn.disabled = true;
          prevQuestionBtn.disabled = false;
        }

        const progressCircleToHighlight = progressBar.querySelector("div:not(.progress-done)");
        progressCircleToHighlight.classList.add("progress-done")
      }

      nextQuestionBtn.onclick = () => gotoNextQuestion()

      prevQuestionBtn.onclick = (e) => {
        const q = document.getElementsByClassName("question-card active")[0];
        const qNr = Number(q.id.slice(1));
        const nextQuestionCard = document.getElementById(`q${qNr - 1}`);
        if (!nextQuestionCard) {
          prevQuestionBtn.disabled = true;
          nextQuestionBtn.disabled = false;
        }
        nextQuestionCard.classList.remove("hidden");
        nextQuestionCard.classList.add("active")
        q.classList.remove("active");
        q.classList.add("hidden");
        if (qNr - 2 == 0) {
          prevQuestionBtn.disabled = true;
          nextQuestionBtn.disabled = false;
        }
        const circles = progressBar.querySelectorAll(".progress-done");
        const progressCircleToHighlight = circles[circles.length - 1];
        progressCircleToHighlight.classList.remove("progress-done")

      }

      document.querySelectorAll(".question-choice-container > label")
        .forEach((element) => {
          element.onclick = () => {
            gotoNextQuestion()
            // console.log(element);

            // if (!element.htmlFor) return;
            // const questionChoice = element.htmlFor;

            // const match = questionChoice.match(/q(\d+)c(\d+)/);

            // if (!match) return;

            // const qNr = Number(match[1]);
            // const cNr = Number(match[2]);


          }
        })
    </script>
</body>

</html>