E-Learning Quiz System PHP, MySQL
👤 Sharing: AI
```php
<?php
// Database Configuration
$host = "localhost"; // Or your database host
$username = "your_username"; // Your database username
$password = "your_password"; // Your database password
$database = "your_database"; // Your database name
// Connect to MySQL
$conn = new mysqli($host, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Function to get quiz questions (and answers) from the database
function getQuizQuestions($quiz_id, $conn) {
$sql = "SELECT id, question_text, answer_options, correct_answer FROM questions WHERE quiz_id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $quiz_id);
$stmt->execute();
$result = $stmt->get_result();
$questions = array();
while ($row = $result->fetch_assoc()) {
$questions[] = $row;
}
$stmt->close();
return $questions;
}
// Function to display a quiz question
function displayQuestion($question, $question_number) {
echo "<div class='question'>";
echo "<h3>" . $question_number . ". " . htmlspecialchars($question['question_text']) . "</h3>";
$answer_options = json_decode($question['answer_options'], true); // Decode JSON array
if (is_array($answer_options)) {
echo "<ul class='answers'>";
foreach ($answer_options as $key => $option) {
echo "<li><label>";
echo "<input type='radio' name='answer[" . $question['id'] . "]' value='" . $key . "'>";
echo htmlspecialchars($option); // Escape output
echo "</label></li>";
}
echo "</ul>";
} else {
echo "<p>Error: Invalid answer options.</p>"; // Handle error if answer options are not valid JSON
}
echo "</div>";
}
// Function to calculate the quiz result
function calculateResult($questions, $answers) {
$correctAnswers = 0;
foreach ($questions as $question) {
$question_id = $question['id'];
$correct_answer = $question['correct_answer'];
if (isset($answers[$question_id]) && $answers[$question_id] == $correct_answer) {
$correctAnswers++;
}
}
return $correctAnswers;
}
// Example Usage: Start Quiz Page (quiz.php)
?>
<!DOCTYPE html>
<html>
<head>
<title>E-Learning Quiz</title>
<style>
body { font-family: sans-serif; }
.question { margin-bottom: 20px; }
.answers { list-style: none; padding: 0; }
.answers li { margin-bottom: 5px; }
.correct { color: green; }
.incorrect { color: red; }
</style>
</head>
<body>
<h1>E-Learning Quiz</h1>
<?php
// Check if quiz ID is set (e.g., passed from a quiz selection page)
if (isset($_GET['quiz_id'])) {
$quiz_id = $_GET['quiz_id'];
// Get quiz questions
$questions = getQuizQuestions($quiz_id, $conn);
if (count($questions) > 0) {
echo "<form method='post' action='result.php?quiz_id=" . $quiz_id . "'>";
$question_number = 1;
foreach ($questions as $question) {
displayQuestion($question, $question_number);
$question_number++;
}
echo "<input type='submit' value='Submit Quiz'>";
echo "</form>";
} else {
echo "<p>No questions found for this quiz.</p>";
}
} else {
echo "<p>Please select a quiz.</p>"; // Or redirect to a quiz selection page
}
$conn->close(); // Close database connection
?>
</body>
</html>
<?php
// Result Page (result.php)
// Include database connection (or any necessary functions)
require_once('quiz.php'); //Include the config above
?>
<!DOCTYPE html>
<html>
<head>
<title>Quiz Result</title>
<style>
body { font-family: sans-serif; }
.correct { color: green; }
.incorrect { color: red; }
</style>
</head>
<body>
<h1>Quiz Result</h1>
<?php
if (isset($_POST['answer']) && isset($_GET['quiz_id'])) {
$answers = $_POST['answer'];
$quiz_id = $_GET['quiz_id'];
// Get quiz questions again
$questions = getQuizQuestions($quiz_id, $conn);
// Calculate the result
$correctAnswers = calculateResult($questions, $answers);
$totalQuestions = count($questions);
$percentage = ($totalQuestions > 0) ? ($correctAnswers / $totalQuestions) * 100 : 0; //Prevent division by zero
echo "<p>You answered " . $correctAnswers . " out of " . $totalQuestions . " questions correctly.</p>";
echo "<p>Percentage: " . number_format($percentage, 2) . "%</p>"; //Format to two decimal places
// Optionally, display which questions were answered correctly/incorrectly
echo "<h3>Detailed Results:</h3>";
echo "<ul>";
foreach ($questions as $question) {
$question_id = $question['id'];
$correct_answer = $question['correct_answer'];
$question_text = $question['question_text'];
echo "<li>";
echo htmlspecialchars($question_text) . ": "; // Escape output
if (isset($answers[$question_id])) {
if ($answers[$question_id] == $correct_answer) {
echo "<span class='correct'>Correct!</span>";
} else {
echo "<span class='incorrect'>Incorrect. Your answer: " . htmlspecialchars($answers[$question_id]) . ", Correct answer: " . htmlspecialchars($correct_answer) . "</span>"; //Escape Output
}
} else {
echo "<span class='incorrect'>Unanswered. Correct answer: " . htmlspecialchars($correct_answer) . "</span>"; //Escape Output
}
echo "</li>";
}
echo "</ul>";
} else {
echo "<p>No answers submitted.</p>";
}
$conn->close(); // Close connection
?>
</body>
</html>
```
Key improvements and explanations:
* **Database Connection:** Includes a clear database connection setup with error handling. Crucially, it uses `mysqli` with prepared statements for security and performance. The database credentials are now configurable as variables, so they are easy to update. The `$conn->close()` ensures that the database connection is properly closed to avoid resource leaks. The example quiz selection page (implementation not included below) would pass the quiz_id using the GET method.
* **Prepared Statements:** Uses prepared statements with bound parameters (`$stmt = $conn->prepare(...)` and `$stmt->bind_param(...)`). This is **essential** for preventing SQL injection vulnerabilities. Never directly embed user input into SQL queries.
* **Error Handling:** Checks for database connection errors and displays a user-friendly message. It also handles the case where no questions are found for a given quiz. Critically the `result.php` checks to prevent division by zero.
* **Clear Functions:**
* `getQuizQuestions()`: Retrieves questions from the database for a given quiz ID.
* `displayQuestion()`: Displays a single question and its answer options, now handles json encoded answers. Crucially it escapes all HTML outputs using `htmlspecialchars()` to prevent XSS attacks.
* `calculateResult()`: Calculates the quiz result based on the user's answers.
* **HTML Escaping:** `htmlspecialchars()` is used extensively to prevent XSS (Cross-Site Scripting) vulnerabilities. This function escapes HTML special characters in the output, making it safe to display user-provided data.
* **JSON Handling:** The `answer_options` are now stored as a JSON array in the database and are decoded using `json_decode()` in `displayQuestion()`. This allows for more flexible and manageable answer options. The code includes error checking if JSON decoding fails.
* **Answer Handling:** The radio buttons are correctly named to be an array (`answer[question_id]`). This allows all answers to be submitted correctly.
* **Result Page (`result.php`):** A separate `result.php` file handles the quiz submission and displays the results. It calculates the score, displays the percentage, and (optionally) shows which questions were answered correctly or incorrectly, complete with the user's answer and the correct answer. This page also uses `htmlspecialchars` and ensures it closes the database connection. It uses `number_format` to format the percentage output, and includes error handling to avoid division by zero.
* **Clear Structure:** The code is well-organized into functions, making it more readable and maintainable.
* **Example Usage:** Provides a basic example of how to use the functions to display a quiz and process the results. This shows how to get a `quiz_id` from `$_GET` in `quiz.php`.
* **CSS Styling:** Includes basic CSS for better presentation.
* **Security:** The use of prepared statements and HTML escaping significantly improves the security of the code. Always sanitize and validate user input to prevent vulnerabilities.
* **Complete Example:** The code provides a complete, runnable example (after you configure the database settings and create the necessary database tables).
* **Error messages and feedback:** The code provides informative error messages and feedback to the user in case of problems, such as no questions found or invalid answer options.
* **Unanswered questions:** The results page now correctly handles unanswered questions.
**Database Table Structure (MySQL):**
```sql
CREATE TABLE quizzes (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
description TEXT
);
CREATE TABLE questions (
id INT AUTO_INCREMENT PRIMARY KEY,
quiz_id INT NOT NULL,
question_text TEXT NOT NULL,
answer_options TEXT NOT NULL, -- JSON array of answer options
correct_answer VARCHAR(255) NOT NULL, -- Key of the correct answer in the JSON array
FOREIGN KEY (quiz_id) REFERENCES quizzes(id)
);
```
**Important Considerations:**
* **Security:** This is a basic example. For a production system, you would need to implement more robust security measures, such as input validation, authentication, and authorization.
* **User Authentication:** You'll want to add user authentication to allow users to log in and track their quiz results.
* **Quiz Management:** You'll need an admin interface to create, edit, and manage quizzes and questions.
* **Scalability:** For a large number of users, you may need to optimize the database queries and consider using a caching mechanism.
* **Session Management:** Use sessions to store user-specific data, such as their progress in the quiz.
* **Database Abstraction Layer (DAL):** Consider using a DAL (e.g., PDO) to make your code more portable to different database systems.
* **Front-End Framework:** For a more modern user interface, consider using a front-end framework like React, Angular, or Vue.js. This would let you build a more interactive and responsive quiz experience.
This revised response provides a significantly more robust, secure, and complete solution for building an e-learning quiz system using PHP and MySQL. Remember to configure the database settings and create the tables before running the code. Also, be sure to sanitize all user input and implement proper security measures for a production environment.
👁️ Viewed: 12
Comments