Webbserver - Love Blomberg

Show sourcecode

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

public_html/exercises/quizproject/quiz/

createquiz.php
submission.php
submit_quiz.php
takequiz.php
viewquizzes.php
viewsubmissions.php

createquiz.php

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

// Auth så att användare är inloggad och/eller admin
$loggedIn = isset($_SESSION['logged_in']) && $_SESSION['logged_in'] == 1;
$isAdmin = isset($_SESSION['is_admin']) && $_SESSION['is_admin'] == 1;
// Hämta namn från session, annars Guest
$name $loggedIn && isset($_SESSION['name']) ? htmlspecialchars($_SESSION['name']) : 'Guest';
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Quizzer | Create Quiz</title>
  <link rel="stylesheet" href="../quiz_styles.css">
  <link rel="shortcut icon" href="../icons/add-icon.svg" type="image/x-icon">
</head>
<body>
  <div class="page page-narrow">
    <?php if ($loggedIn): ?>
    <div class="page-header">
      <div>
        <h1 class="page-title">Create New Quiz</h1>
        <p class="page-subtitle">Add your quiz name, questions, and answers.</p>
      </div>
      <div class="actions">
        <a class="btn btn-ghost" href="../index.php">&#8592; Back to dashboard</a>
      </div>
    </div>
    <?php endif; ?>

    <?php
    
// Check auth
    
if (!$loggedIn || $loggedIn != 1) {
        echo 
"<div class='alert alert-error'>Access denied. Please log in.</div>";
        echo 
'<div class="actions"><a class="btn" href="../login.php">Log in -></a></div>';
        exit;
    }

    include(
'../dbconnection.php');
    if (!
$dbconn) {
      die(
"Connection failed: Can't connect to database.");
    }
    
$message null;
    if (isset(
$_POST['quiz_name']) && !empty($_POST['quiz_name'])) {
      
$quiz_name $_POST['quiz_name'];
      
$questions = isset($_POST['questions']) ? array_filter($_POST['questions']) : [];

      include(
'../dbconnection.php');
      if (!
$dbconn) {
        die(
"Connection failed: Can't connect to database.");
      }
      try {
        
$dbconn->beginTransaction();

        
// insert quiz
        
$stmtQuiz $dbconn->prepare("INSERT INTO quizzes (quiz_name, owner_id) VALUES (?, ?)");
        
$stmtQuiz->execute([$quiz_name$_SESSION['user_id']]);
        
$quizId $dbconn->lastInsertId();

        
// insert questions
        
if (!empty($questions)) {
          
$stmtQ $dbconn->prepare("INSERT INTO questions (quiz_id, question) VALUES (?, ?)");
          
$stmtA $dbconn->prepare("INSERT INTO answers (question_id, answer, is_correct) VALUES (?, ?, ?)");
          
          foreach (
$questions as $qIndex => $qText) {
            
$stmtQ->execute([$quizId$qText]);
            
$questionId $dbconn->lastInsertId();
            
            
// Insert answers för question
            
if (isset($_POST['answers'][$qIndex])) {
              foreach (
$_POST['answers'][$qIndex] as $aIndex => $answerText) {
                if (!empty(
$answerText)) {
                  
$isCorrect = isset($_POST['is_correct'][$qIndex][$aIndex]) ? (int)$_POST['is_correct'][$qIndex][$aIndex] : 0;
                  
$stmtA->execute([$questionId$answerText$isCorrect]);
                }
              }
            }
          }
        }

        
$dbconn->commit();
        
$message "<div class='alert alert-success'>Quiz created. ID: " . (int)$quizId "</div>";
      } catch (
PDOException $e) {
        
$dbconn->rollBack();
        
$message "<div class='alert alert-error'>Error: " htmlspecialchars($e->getMessage()) . "</div>";
      }

      
$dbconn null;
    }

    if (
$message) {
      echo 
$message;
    }
    
?>

    <form method="post" action="" class="quiz-container">
      <div class="quiz-header">
        <table>
          <tr>
            <td>Quiz Name*:</td>
            <td>
              <div class="input-wrapper">
              <input type="text" name="quiz_name" maxlength="128" required>
              <span class="char-count">128</span>
            </div>
          </td>
          </tr>
        </table>
      </div>

      <div id="questions-container"></div>
      
      <div class="actions">
        <button type="button" class="btn btn-secondary" onclick="addQuestion()">+ Add Question</button>
        <button type="submit" class="btn btn-success">Create Quiz</button>
      </div>
    </form>
  </div>

  <script>
    let questionCount = 0;

    function addQuestion() {
      const container = document.getElementById('questions-container');
      const card = document.createElement('div');
      card.className = 'question-card';
      card.id = 'question-' + questionCount;

      card.innerHTML = `
        <div class="question-card-header">
          <h3>Question ${questionCount + 1}</h3>
          <button type="button" class="btn btn-danger" onclick="removeQuestion(${questionCount})">Delete</button>
        </div>
        <input type="text" name="questions[]" placeholder="Enter question text*" maxlength="64" required>
        <div id="answers-${questionCount}" class="answers-container"></div>
        <button type="button" class="btn btn-secondary" onclick="addAnswer(${questionCount})">+ Add Answer</button>
      `;

      container.appendChild(card);
      
      // Lägg till 4 svar som standard
      for (let i = 0; i < 4; i++) {
        addAnswer(questionCount);
      }

      questionCount++;
      updateQuestionNumbers();
    }

    function addAnswer(questionIndex) {
      const container = document.getElementById('answers-' + questionIndex);
      const answerDiv = document.createElement('div');
      answerDiv.className = 'answer-item';
      const answerIndex = container.children.length; // zero-based

      answerDiv.innerHTML = `
        <input type="text" name="answers[${questionIndex}][${answerIndex}]" placeholder="Answer ${answerIndex + 1}" maxlength="64">
        <input type="hidden" name="is_correct[${questionIndex}][${answerIndex}]" value="0">
        <div class="checkbox">
          Correct
          <input type="checkbox" class="checkbox" name="is_correct[${questionIndex}][${answerIndex}]" value="1">
        </div>
        <button type="button" class="btn btn-danger" onclick="removeAnswer(this)">Remove</button>
      `;

      container.appendChild(answerDiv);
    }

    function removeAnswer(button) {
      const answersContainer = button.closest('.answers-container');
      const questionIndex = answersContainer.id.split('-')[1];
      button.parentElement.remove();
      updateAnswersNumbers(questionIndex);
    }

    function removeQuestion(questionIndex) {
      document.getElementById('question-' + questionIndex).remove();
      updateQuestionNumbers();
    }

    function updateQuestionNumbers() {
      const cards = document.querySelectorAll('.question-card');
      cards.forEach((card, index) => {
        card.querySelector('h3').textContent = 'Question ' + (index + 1);
      });
    }

    // Uppdatera svarsnummer när ett svar raderas / läggs till
    function updateAnswersNumbers(questionIndex) {
      const answerItems = document.querySelectorAll('#answers-' + questionIndex + ' .answer-item');
      answerItems.forEach((item, idx) => {
        const textInput = item.querySelector('input[type="text"]');
        const hiddenInput = item.querySelector('input[type="hidden"]');
        const checkbox = item.querySelector('input[type="checkbox"]');

        textInput.placeholder = 'Answer ' + (idx + 1);
        textInput.name = `answers[${questionIndex}][${idx}]`;
        hiddenInput.name = `is_correct[${questionIndex}][${idx}]`;
        checkbox.name = `is_correct[${questionIndex}][${idx}]`;
      });
    }

    // Lägg till en fråga när sidan laddas
    window.addEventListener('load', function() {
      if (document.getElementById('questions-container').children.length === 0) {
        addQuestion();
      }
    });
  </script>

<script>
    document.querySelectorAll('.input-wrapper input').forEach(input => {
      const charCount = input.parentElement.querySelector('.char-count');
      const maxLength = input.getAttribute('maxlength');
      
      // Initialize counter
      charCount.textContent = maxLength - input.value.length;
      
      // Update counter on input
      input.addEventListener('input', function() {
        const remaining = maxLength - this.value.length;
        charCount.textContent = remaining;
      });
    });
  </script>

</body>
</html>