online learning platform project in php and mysql

Rashmi Mishra
0

 

Online learning platform project 

In PHP and MYSQL

The online_learning_platform project is a web-based platform designed for managing online courses, assignments, quizzes, and student progress. This type of platform typically allows administrators, instructors, and students to interact with one another in a virtual learning environment. Here’s a summary of its main features and components:


Key Features

User Management:

  1. Admin: Manages the platform, including users (students and instructors), courses, and overall settings.
  2. Instructor: Creates and manages courses, assignments, and quizzes. Monitors student progress.
  3. Student: Enrolls in courses, submits assignments, takes quizzes, and tracks their own progress.

Course Management:

  1. Admins and instructors can create, update, and delete courses.
  2. Courses are organized by modules or topics, which can include text, video, or downloadable resources.

Assignment and Quiz Management:

  1. Instructors can create assignments and quizzes for their courses.
  2. Students can submit assignments and complete quizzes. Instructors can then review submissions and grade quizzes.

Progress Tracking and Reporting:

  1. Students can track their own progress in the courses they’re enrolled in.
  2. Admins and instructors can generate reports on student progress and course performance.

Notifications and Communication:

  1. The platform can send notifications for new assignments, quiz results, and important updates.
  2. Some platforms also include communication tools for messaging between students and instructors.

Project Structure

The project is built using core PHP and MySQL for database management. 

The structure includes directories for:

  1. Configuration: Database connection and global settings.
  2. Controllers: Logic that handles user requests and connects to models.
  3. Models: Data interaction with the MySQL database.
  4. Views: Front-end templates for different pages (HTML and PHP).
  5. Helpers and Services: Additional utility classes for common tasks and specific services like email and report generation.
  6. Assets and Storage: Static files (CSS, JavaScript, images) and storage for user uploads and logs.

How It Works

  1. Admins have access to an admin dashboard where they can manage users, courses, and monitor platform activity.
  2. Instructors have access to course management tools, allowing them to create content, assignments, and quizzes.

Students access a dashboard to view available courses, enroll in them, and participate in assignments and quizzes to track their learning progress.

This platform aims to replicate many of the features of popular online learning systems, offering a structured way to manage educational content and interact with students in an organized and efficient manner.



Database Tables


1. users Table
Stores information about all users, including admins, instructors, and students.

Column Type Description
id INT Primary key, auto-incremented user ID
name VARCHAR(255) User’s full name
email VARCHAR(255) User’s email (unique)
password VARCHAR(255) Hashed password
role ENUM('admin', 'instructor', 'student') Role of the user
created_at TIMESTAMP Timestamp of user creation
updated_at TIMESTAMP Timestamp of last user update
2. courses Table
Stores course information.

Column Type Description
id INT Primary key, auto-incremented course ID
title VARCHAR(255) Course title
description TEXT Course description
instructor_id INT Foreign key referencing users.id
created_at TIMESTAMP Timestamp of course creation
updated_at TIMESTAMP Timestamp of last course update
3. modules Table
Stores information about course modules or sections.

Column Type Description
id INT Primary key, auto-incremented module ID
course_id INT Foreign key referencing courses.id
title VARCHAR(255) Module title
content TEXT Content or description of the module
created_at TIMESTAMP Timestamp of module creation
updated_at TIMESTAMP Timestamp of last module update
4. assignments Table
Stores assignments related to each course module.

Column Type Description
id INT Primary key, auto-incremented assignment ID
module_id INT Foreign key referencing modules.id
title VARCHAR(255) Assignment title
description TEXT Assignment instructions
due_date DATE Due date for the assignment
created_at TIMESTAMP Timestamp of assignment creation
updated_at TIMESTAMP Timestamp of last assignment update
5. quizzes Table
Stores quizzes related to each course module.

Column Type Description
id INT Primary key, auto-incremented quiz ID
module_id INT Foreign key referencing modules.id
title VARCHAR(255) Quiz title
created_at TIMESTAMP Timestamp of quiz creation
updated_at TIMESTAMP Timestamp of last quiz update
6. questions Table
Stores questions for each quiz.

Column Type Description
id INT Primary key, auto-incremented question ID
quiz_id INT Foreign key referencing quizzes.id
question_text TEXT Question text
created_at TIMESTAMP Timestamp of question creation
updated_at TIMESTAMP Timestamp of last question update

7. choices Table
Stores answer choices for each quiz question.

Column Type Description
id INT Primary key, auto-incremented choice ID
question_id INT Foreign key referencing questions.id
choice_text VARCHAR(255) Text of the answer choice
is_correct BOOLEAN Indicates if the choice is correct

8. submissions Table
Stores student submissions for assignments.

Column Type Description
id INT Primary key, auto-incremented submission ID
assignment_id INT Foreign key referencing assignments.id
student_id INT Foreign key referencing users.id
file_path VARCHAR(255) Path to the submitted file
grade FLOAT Grade received for the submission
submitted_at TIMESTAMP Timestamp of submission

9. quiz_attempts Table

Tracks each student’s quiz attempts and their scores.

Column Type Description
id INT Primary key, auto-incremented attempt ID
quiz_id INT Foreign key referencing quizzes.id
student_id INT Foreign key referencing users.id
score FLOAT Score received for the quiz
attempt_date TIMESTAMP Timestamp of the quiz attempt

10. notifications Table

Stores notifications for users.

Column Type Description
id INT Primary key, auto-incremented notification ID
user_id INT Foreign key referencing users.id
message TEXT Notification message
is_read BOOLEAN Whether the notification has been read
created_at TIMESTAMP Timestamp of notification creation

11. enrollments Table

Tracks students' enrollment in courses.

Column Type Description
id INT Primary key, auto-incremented enrollment ID
student_id INT Foreign key referencing users.id
course_id INT Foreign key referencing courses.id
enrolled_at TIMESTAMP Timestamp of course enrollment

12. activity_logs Table

Tracks user activities for auditing purposes.

Column Type Description
id INT Primary key, auto-incremented log ID
user_id INT Foreign key referencing users.id
activity TEXT Description of the user activity
created_at TIMESTAMP Timestamp of the activity

This table structure provides a solid database foundation to support user roles, course content management, assessments, tracking, and notifications for the online_learning_platform. we can modify or extend the tables based on additional specific requirements for the project.


Project Structure
online_learning_platform/
├── assets/
│   ├── css/
│   │   └── styles.css
│   ├── js/
│   │   └── scripts.js
│   └── images/
│       └── (images for the platform)
├── config/
│   └── config.php
├── controllers/
│   ├── AuthController.php
│   ├── CourseController.php
│   ├── ModuleController.php
│   ├── AssignmentController.php
│   ├── QuizController.php
│   ├── SubmissionController.php
│   ├── NotificationController.php
│   └── UserController.php
├── helpers/
│   └── functions.php
├── models/
│   ├── User.php
│   ├── Course.php
│   ├── Module.php
│   ├── Assignment.php
│   ├── Quiz.php
│   ├── Submission.php
│   ├── Notification.php
│   └── Enrollment.php
├── views/
│   ├── layouts/
│   │   ├── header.php
│   │   ├── sidebar.php
│   │   └── footer.php
│   ├── auth/
│   │   ├── login.php
│   │   └── register.php
│   ├── dashboard/
│   │   └── dashboard.php
│   ├── courses/
│   │   ├── course_list.php
│   │   ├── course_create.php
│   │   ├── course_edit.php
│   │   └── course_view.php
│   ├── modules/
│   │   ├── module_list.php
│   │   ├── module_create.php
│   │   └── module_edit.php
│   ├── assignments/
│   │   ├── assignment_list.php
│   │   ├── assignment_create.php
│   │   └── assignment_view.php
│   ├── quizzes/
│   │   ├── quiz_list.php
│   │   ├── quiz_create.php
│   │   └── quiz_view.php
│   └── notifications/
│       └── notifications.php
└── index.php
└── .htaccess

Folder and File Descriptions
1. assets/
Contains static assets like CSS, JavaScript, and images.
css/styles.css: Main stylesheet for styling the platform.
js/scripts.js: JavaScript file for client-side interactions.
images/: Stores images for the platform, like logos and icons.
2. config/
Configuration files for database connections and global settings.
config.php: Contains database credentials and any global configuration variables.
3. controllers/
Handles the logic and interaction between the models and views.
AuthController.php: Manages user authentication (login, registration, logout).
CourseController.php: Handles course-related actions (list, create, edit, view).
ModuleController.php: Manages course modules (list, create, edit).
AssignmentController.php: Handles assignment-related actions (list, create, view).
QuizController.php: Manages quiz actions (list, create, view).
SubmissionController.php: Manages student assignment submissions.
NotificationController.php: Handles notifications for users.
UserController.php: Manages user-related actions and profile settings.
4. helpers/
Utility functions and reusable code snippets.
functions.php: Contains helper functions like input validation, redirects, and file uploads.
5. models/
Represents the data structure and interacts with the database.
User.php: Handles user-related database operations.
Course.php: Manages course-related database operations.
Module.php: Manages module-related database operations.
Assignment.php: Handles assignment-related database operations.
Quiz.php: Manages quiz-related database operations.
Submission.php: Manages submission-related database operations.
Notification.php: Handles notification-related database operations.
Enrollment.php: Manages course enrollments for students.
6. views/
Contains the HTML templates for different pages on the platform.
layouts/: 
Reusable layout components.
header.php: Contains HTML for the header, navigation, and top bar.
sidebar.php: Sidebar for navigation (customized based on user roles).
footer.php: HTML for the footer section.
auth/: 
Authentication pages.
login.php: User login form.
register.php: User registration form.
dashboard/: 
Main dashboard.
dashboard.php: Displays the dashboard with user-specific content (admin, instructor, or student).
courses/: 
Course management pages.
course_list.php: List of all courses.
course_create.php: Form for creating a new course.
course_edit.php: Form for editing an existing course.
course_view.php: Detailed view of a course, including modules and content.
modules/: 
Module management pages.
module_list.php: List of all modules for a course.
module_create.php: Form for creating a new module.
module_edit.php: Form for editing a module.
assignments/: 
Assignment management pages.
assignment_list.php: List of all assignments for a course.
assignment_create.php: Form for creating an assignment.
assignment_view.php: View an assignment and upload submissions.
quizzes/: 
Quiz management pages.
quiz_list.php: List of all quizzes for a course.
quiz_create.php: Form for creating a new quiz.
quiz_view.php: View a quiz, attempt, and display results.
notifications/: 
Notifications page.
notifications.php: Displays user-specific notifications.
7. Root Files
index.php: Entry point to the application. Redirects users to the appropriate pages based on their role.
.htaccess: Configures URL rewriting to handle clean URLs and redirect users based on request types.


Source Code :

Styles.css:

/* Global Styles */
body {
    font-family: Arial, sans-serif;
    line-height: 1.6;
    margin: 0;
    padding: 0;
    background-color: #f4f4f4;
    color: #333;
}

h1, h2, h3 {
    color: #333;
}

/* Container */
.container {
    width: 80%;
    margin: auto;
    overflow: hidden;
}

/* Header */
header {
    background: #35424a;
    color: #ffffff;
    padding: 20px 0;
    text-align: center;
}

header h1 {
    margin: 0;
}

/* Navigation */
nav {
    background: #35424a;
    color: #ffffff;
    padding: 15px;
}

nav a {
    color: #ffffff;
    text-decoration: none;
    padding: 10px 15px;
}

nav a:hover {
    background: #e8491d;
    color: #ffffff;
}

/* Form Styles */
form {
    background: #ffffff;
    padding: 20px;
    border-radius: 5px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    margin: 20px 0;
}

form input, form textarea, form button {
    width: 100%;
    padding: 10px;
    margin: 10px 0;
    border: 1px solid #ccc;
    border-radius: 5px;
}

form button {
    background: #35424a;
    color: #ffffff;
    border: none;
    cursor: pointer;
}

form button:hover {
    background: #e8491d;
}

/* Course List */
.course-list {
    list-style-type: none;
    padding: 0;
}

.course-list li {
    background: #ffffff;
    margin: 10px 0;
    padding: 15px;
    border-radius: 5px;
    box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
    display: flex;
    justify-content: space-between;
}

.course-list li form {
    margin: 0;
}

/* Footer */
footer {
    text-align: center;
    padding: 20px;
    background: #35424a;
    color: #ffffff;
    position: relative;
    bottom: 0;
    width: 100%;
}

.footer-links {
    margin: 0;
    padding: 0;
    list-style-type: none;
}

.footer-links li {
    display: inline;
    margin: 0 10px;
}

/* Responsive Styles */
@media (max-width: 768px) {
    .container {
        width: 100%;
    }

    nav {
        text-align: center;
    }

    nav a {
        display: block;
        padding: 10px;
    }
}

Explanation of Styles
Global Styles: Sets a consistent font family, line height, and background color for the body.
Header: Styles the header with a background color, text color, and padding.
Navigation: Styles the navigation links, adding padding and hover effects.
Form Styles: Provides styles for forms, including input fields, textareas, and buttons, enhancing the appearance with shadows and rounded corners.
Course List: Styles the course list, making it visually appealing with backgrounds and shadows for each course item.
Footer: Styles the footer similarly to the header for consistency.
Responsive Styles: Adds media queries to ensure the layout is responsive and looks good on smaller screens.
Integration
Make sure to link this styles.css file in your HTML files, typically in the <head> section:

<link rel="stylesheet" href="css/styles.css">

public/js/scripts.js
// Wait for the DOM to fully load before executing scripts
document.addEventListener("DOMContentLoaded", function () {
    // Handle form submission
    const forms = document.querySelectorAll("form");
    forms.forEach(form => {
        form.addEventListener("submit", function (event) {
            // Prevent default form submission
            event.preventDefault();
            validateForm(this);
        });
    });

    // Validate form fields
    function validateForm(form) {
        const inputs = form.querySelectorAll("input, textarea");
        let isValid = true;

        inputs.forEach(input => {
            if (input.type !== "submit" && !input.value.trim()) {
                isValid = false;
                input.classList.add("error");
                showError(input, "This field is required.");
            } else {
                input.classList.remove("error");
                clearError(input);
            }
        });

        if (isValid) {
            // If the form is valid, proceed with form submission
            submitForm(form);
        }
    }

    // Show error message for invalid fields
    function showError(input, message) {
        let errorElement = input.nextElementSibling;

        if (!errorElement || !errorElement.classList.contains("error-message")) {
            errorElement = document.createElement("div");
            errorElement.className = "error-message";
            errorElement.style.color = "red";
            input.parentNode.insertBefore(errorElement, input.nextSibling);
        }
        errorElement.innerText = message;
    }

    // Clear error message
    function clearError(input) {
        const errorElement = input.nextElementSibling;
        if (errorElement && errorElement.classList.contains("error-message")) {
            errorElement.innerText = "";
        }
    }

    // Function to handle form submission
    function submitForm(form) {
        const formData = new FormData(form);

        fetch(form.action, {
            method: form.method,
            body: formData,
        })
        .then(response => response.json())
        .then(data => {
            // Handle success or error
            if (data.success) {
                alert("Form submitted successfully!");
                form.reset(); // Reset the form
            } else {
                alert("Error: " + data.message);
            }
        })
        .catch(error => {
            console.error("Error submitting the form:", error);
            alert("An error occurred. Please try again later.");
        });
    }
});
Explanation of scripts.js
DOMContentLoaded: Ensures the script runs only after the entire DOM has been loaded.
Form Handling: Attaches event listeners to all forms for submission. When a form is submitted, it calls validateForm().
Form Validation: Checks if all input fields are filled out. If a field is empty, it adds an error class and displays an error message. Valid fields will remove any error messages.
Error Handling: Functions to show and clear error messages.
Form Submission: If the form is valid, it sends the form data using fetch to the server-side script defined in the form's action attribute. It processes the response and alerts the user based on success or failure.
Integration
Make sure to link this scripts.js file in your HTML files, typically before the closing </body> tag:

<script src="js/scripts.js"></script>
This will ensure that your JavaScript functionality works correctly on the client side, enhancing user interaction with your Online Learning Platform. You can further customize the scripts based on additional features and functionalities required for your project.

1.Database Connection Files
config/config.php
This file contains the database connection settings.

<?php
// Database configuration
define('DB_HOST', 'localhost');
define('DB_USER', 'your_db_user');
define('DB_PASS', 'your_db_password');
define('DB_NAME', 'online_learning_platform');

// Create a connection
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
?>
2. Controllers
controllers/AuthController.php
This controller will handle authentication-related functionalities, such as user login and logout, and potentially password reset functionality if you wish to expand upon it later.

<?php
require_once 'models/User.php';

class AuthController {
    // Display the login form
    public function showLoginForm() {
        require_once 'views/auth/login.php';
    }

    // Handle user login
    public function login() {
        session_start(); // Start a session

        $email = $_POST['email'];
        $password = $_POST['password'];

        // Retrieve user by email
        $user = User::getUserByEmail($email);

        // Verify password and set session variables
        if ($user && password_verify($password, $user['password'])) {
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['role'] = $user['role'];

            header('Location: index.php?action=dashboard'); // Redirect to dashboard
        } else {
            $error = "Invalid email or password.";
            require_once 'views/auth/login.php'; // Show login form with error message
        }
    }

    // Logout the user
    public function logout() {
        session_start(); // Start a session
        session_destroy(); // Destroy the session
        header('Location: index.php?action=login'); // Redirect to login page
    }

    // Display the password reset form
    public function showResetForm() {
        require_once 'views/auth/reset.php';
    }

    // Handle password reset request
    public function resetPassword() {
        $email = $_POST['email'];

        // Here you would typically check if the email exists and send a password reset link
        // For demonstration, we'll assume success

        // Send reset email (implement your own email sending logic)
        // mail($email, "Password Reset", "Click here to reset your password...");

        $message = "A password reset link has been sent to your email.";
        require_once 'views/auth/reset.php'; // Show reset form with success message
    }
}
Explanation of AuthController.php
  1. ShowLoginForm Method: Displays the user login form.
  2. Login Method: Handles user login logic. It retrieves the user by email and verifies the password. If the login is successful, it sets session variables for the user ID and role, then redirects to the dashboard. If login fails, it returns to the login form with an error message.
  3. Logout Method: Destroys the session to log the user out and redirects them to the login page.
  4. ShowResetForm Method: Displays the password reset form.
  5. ResetPassword Method: Handles the password reset request. This could involve checking if the email exists in the database and sending a password reset link (this functionality requires email handling, which would be implemented separately).
Integration
You will need to set up routing in your application to connect actions to this controller. Here’s an example routing mechanism in index.php:

if (isset($_GET['action'])) {
    $action = $_GET['action'];

    switch ($action) {
        // Other cases...

        case 'login':
            $controller = new AuthController();
            $controller->showLoginForm();
            break;
        case 'login_user':
            $controller = new AuthController();
            $controller->login();
            break;
        case 'logout':
            $controller = new AuthController();
            $controller->logout();
            break;
        case 'reset_password':
            $controller = new AuthController();
            $controller->showResetForm();
            break;
        case 'send_reset':
            $controller = new AuthController();
            $controller->resetPassword();
            break;
        default:
            // Handle 404
            break;
    }
}
Views
Make sure to create the necessary views:
  1. views/auth/login.php: Login form.
  2. views/auth/reset.php: Password reset form.
This setup provides a foundational structure for handling user authentication within your Online Learning Platform. You can expand the functionality as needed, such as implementing actual email sending for password resets, adding error handling, and improving security measures.

2. controllers/CourseController.php
This controller will manage course-related functionalities, including listing courses, creating, updating, deleting courses, and viewing course details.

<?php
require_once 'models/Course.php';

class CourseController {
    // Display all courses
    public function index() {
        $courses = Course::getAllCourses();
        require_once 'views/courses/index.php'; // View for listing courses
    }

    // Display the form to create a new course
    public function create() {
        require_once 'views/courses/create.php'; // View for course creation
    }

    // Handle course creation
    public function store() {
        $title = $_POST['title'];
        $description = $_POST['description'];
        $instructorId = $_POST['instructor_id']; // Assuming the instructor ID is provided

        if (Course::createCourse($title, $description, $instructorId)) {
            header('Location: index.php?action=courses'); // Redirect to course list
        } else {
            echo "Error creating course.";
        }
    }

    // Display the form to edit an existing course
    public function edit($courseId) {
        $course = Course::getCourseById($courseId);
        require_once 'views/courses/edit.php'; // View for course editing
    }

    // Handle course updates
    public function update($courseId) {
        $title = $_POST['title'];
        $description = $_POST['description'];
        $instructorId = $_POST['instructor_id'];

        if (Course::updateCourse($courseId, $title, $description, $instructorId)) {
            header('Location: index.php?action=courses'); // Redirect to course list
        } else {
            echo "Error updating course.";
        }
    }

    // Handle course deletion
    public function destroy($courseId) {
        if (Course::deleteCourse($courseId)) {
            header('Location: index.php?action=courses'); // Redirect to course list
        } else {
            echo "Error deleting course.";
        }
    }

    // Display course details
    public function show($courseId) {
        $course = Course::getCourseById($courseId);
        require_once 'views/courses/show.php'; // View for course details
    }
}
Explanation of CourseController.php
  1. Index Method: Retrieves all courses and displays them using the index view.
  2. Create Method: Displays the form for creating a new course.
  3. Store Method: Handles the form submission for creating a new course. It retrieves the course title, description, and instructor ID, and calls the model method to save it to the database.
  4. Edit Method: Retrieves the course details by ID and displays the edit form.
  5. Update Method: Handles the form submission for updating an existing course. It updates the course details in the database and redirects to the course list.
  6. Destroy Method: Deletes the specified course and redirects to the course list.
  7. Show Method: Displays the details of a specific course.
Integration
You will need to set up routing in your application to connect actions to this controller. Here’s an example routing mechanism in index.php:

if (isset($_GET['action'])) {
    $action = $_GET['action'];

    switch ($action) {
        // Other cases...

        case 'courses':
            $controller = new CourseController();
            $controller->index();
            break;
        case 'create_course':
            $controller = new CourseController();
            $controller->create();
            break;
        case 'store_course':
            $controller = new CourseController();
            $controller->store();
            break;
        case 'edit_course':
            $controller = new CourseController();
            $controller->edit($_GET['course_id']);
            break;
        case 'update_course':
            $controller = new CourseController();
            $controller->update($_GET['course_id']);
            break;
        case 'delete_course':
            $controller = new CourseController();
            $controller->destroy($_GET['course_id']);
            break;
        case 'show_course':
            $controller = new CourseController();
            $controller->show($_GET['course_id']);
            break;
        default:
            // Handle 404
            break;
    }
}
Views
Make sure to create the necessary views:
  1. views/courses/index.php: List of courses.
  2. views/courses/create.php: Form for creating a new course.
  3. views/courses/edit.php: Form for editing an existing course.
  4. views/courses/show.php: View for displaying course details.
This setup provides a foundational structure for managing courses within your Online Learning Platform. You can expand the functionality as needed based on your project's requirements, such as adding features for course categories, prerequisites, or additional metadata.


controllers/ModuleController.php
This controller will manage the modules associated with courses, including listing modules, creating, updating, deleting modules, and viewing module details.

<?php
require_once 'models/Module.php';

class ModuleController {
    // Display all modules for a specific course
    public function index($courseId) {
        $modules = Module::getModulesByCourseId($courseId);
        require_once 'views/modules/index.php'; // View for listing modules
    }

    // Display the form to create a new module
    public function create($courseId) {
        require_once 'views/modules/create.php'; // View for module creation
    }

    // Handle module creation
    public function store($courseId) {
        $title = $_POST['title'];
        $description = $_POST['description'];

        if (Module::createModule($courseId, $title, $description)) {
            header("Location: index.php?action=modules&course_id=$courseId"); // Redirect to module list
        } else {
            echo "Error creating module.";
        }
    }

    // Display the form to edit an existing module
    public function edit($moduleId) {
        $module = Module::getModuleById($moduleId);
        require_once 'views/modules/edit.php'; // View for module editing
    }

    // Handle module updates
    public function update($moduleId) {
        $title = $_POST['title'];
        $description = $_POST['description'];

        if (Module::updateModule($moduleId, $title, $description)) {
            header("Location: index.php?action=modules&course_id=" . $moduleId); // Redirect to module list
        } else {
            echo "Error updating module.";
        }
    }

    // Handle module deletion
    public function destroy($moduleId) {
        $courseId = Module::getCourseIdByModuleId($moduleId); // Get course ID
        if (Module::deleteModule($moduleId)) {
            header("Location: index.php?action=modules&course_id=$courseId"); // Redirect to module list
        } else {
            echo "Error deleting module.";
        }
    }

    // Display module details
    public function show($moduleId) {
        $module = Module::getModuleById($moduleId);
        require_once 'views/modules/show.php'; // View for module details
    }
}
Explanation of ModuleController.php
  1. Index Methodrm submission for creating a new module. It retrieves the module title and description, and calls the model method to save it to the database.
  2. Edit Method: Retrieves the module details by ID and displays the edit form.
  3. Update Method: Handles the form submission for updating an existing module. It updates the module details in the database and redirects to the module list.
  4. Destroy Method: Deletes the specified module and redirects to the module list.
  5. Show Method: Displays the details of a specific module.
Integration
You will need to set up routing in your application to connect actions to this controller. Here’s an example routing mechanism in index.php:

if (isset($_GET['action'])) {
    $action = $_GET['action'];

    switch ($action) {
        // Other cases...

        case 'modules':
            $controller = new ModuleController();
            $controller->index($_GET['course_id']);
            break;
        case 'create_module':
            $controller = new ModuleController();
            $controller->create($_GET['course_id']);
            break;
        case 'store_module':
            $controller = new ModuleController();
            $controller->store($_GET['course_id']);
            break;
        case 'edit_module':
            $controller = new ModuleController();
            $controller->edit($_GET['module_id']);
            break;
        case 'update_module':
            $controller = new ModuleController();
            $controller->update($_GET['module_id']);
            break;
        case 'delete_module':
            $controller = new ModuleController();
            $controller->destroy($_GET['module_id']);
            break;
        case 'show_module':
            $controller = new ModuleController();
            $controller->show($_GET['module_id']);
            break;
        default:
            // Handle 404
            break;
    }
}
Views
Make sure to create the necessary views:
  1. views/modules/index.php: List of modules for a specific course.
  2. views/modules/create.php: Form for creating a new module.
  3. views/modules/edit.php: Form for editing an existing module.
  4. views/modules/show.php: View for displaying module details.
This setup provides a foundational structure for managing modules within your Online Learning Platform. You can expand the functionality as needed based on your project requirements, such as adding features for module prerequisites, associated assignments, or additional metadata.


controllers/AssignmentController.php
This controller will manage the assignments associated with modules, including listing assignments, creating, updating, deleting assignments, and viewing assignment details.

controllers/AssignmentController.php
<?php
require_once 'models/Assignment.php';

class AssignmentController {
    // Display all assignments for a specific module
    public function index($moduleId) {
        $assignments = Assignment::getAssignmentsByModuleId($moduleId);
        require_once 'views/assignments/index.php'; // View for listing assignments
    }

    // Display the form to create a new assignment
    public function create($moduleId) {
        require_once 'views/assignments/create.php'; // View for assignment creation
    }

    // Handle assignment creation
    public function store($moduleId) {
        $title = $_POST['title'];
        $description = $_POST['description'];
        $dueDate = $_POST['due_date'];

        if (Assignment::createAssignment($moduleId, $title, $description, $dueDate)) {
            header("Location: index.php?action=assignments&module_id=$moduleId"); // Redirect to assignment list
        } else {
            echo "Error creating assignment.";
        }
    }

    // Display the form to edit an existing assignment
    public function edit($assignmentId) {
        $assignment = Assignment::getAssignmentById($assignmentId);
        require_once 'views/assignments/edit.php'; // View for assignment editing
    }

    // Handle assignment updates
    public function update($assignmentId) {
        $title = $_POST['title'];
        $description = $_POST['description'];
        $dueDate = $_POST['due_date'];

        if (Assignment::updateAssignment($assignmentId, $title, $description, $dueDate)) {
            // Get module ID for redirection
            $moduleId = Assignment::getModuleIdByAssignmentId($assignmentId);
            header("Location: index.php?action=assignments&module_id=$moduleId"); // Redirect to assignment list
        } else {
            echo "Error updating assignment.";
        }
    }

    // Handle assignment deletion
    public function destroy($assignmentId) {
        $moduleId = Assignment::getModuleIdByAssignmentId($assignmentId); // Get module ID
        if (Assignment::deleteAssignment($assignmentId)) {
            header("Location: index.php?action=assignments&module_id=$moduleId"); // Redirect to assignment list
        } else {
            echo "Error deleting assignment.";
        }
    }

    // Display assignment details
    public function show($assignmentId) {
        $assignment = Assignment::getAssignmentById($assignmentId);
        require_once 'views/assignments/show.php'; // View for assignment details
    }
}
Explanation of AssignmentController.php
  1. Index Method: Retrieves all assignments for a specific module and displays them using the index view.
  2. Create Method: Displays the form for creating a new assignment associated with a specific module.
  3. Store Method: Handles the form submission for creating a new assignment. It retrieves the assignment title, description, and due date, and calls the model method to save it to the database.
  4. Edit Method: Retrieves the assignment details by ID and displays the edit form.
  5. Update Method: Handles the form submission for updating an existing assignment. It updates the assignment details in the database and redirects to the assignment list.
  6. Destroy Method: Deletes the specified assignment and redirects to the assignment list.
  7. Show Method: Displays the details of a specific assignment.
Integration
You will need to set up routing in your application to connect actions to this controller. Here’s an example routing mechanism in index.php:

if (isset($_GET['action'])) {
    $action = $_GET['action'];

    switch ($action) {
        // Other cases...

        case 'assignments':
            $controller = new AssignmentController();
            $controller->index($_GET['module_id']);
            break;
        case 'create_assignment':
            $controller = new AssignmentController();
            $controller->create($_GET['module_id']);
            break;
        case 'store_assignment':
            $controller = new AssignmentController();
            $controller->store($_GET['module_id']);
            break;
        case 'edit_assignment':
            $controller = new AssignmentController();
            $controller->edit($_GET['assignment_id']);
            break;
        case 'update_assignment':
            $controller = new AssignmentController();
            $controller->update($_GET['assignment_id']);
            break;
        case 'delete_assignment':
            $controller = new AssignmentController();
            $controller->destroy($_GET['assignment_id']);
            break;
        case 'show_assignment':
            $controller = new AssignmentController();
            $controller->show($_GET['assignment_id']);
            break;
        default:
            // Handle 404
            break;
    }
}
Views
Make sure to create the necessary views:
  1. views/assignments/index.php: List of assignments for a specific module.
  2. views/assignments/create.php: Form for creating a new assignment.
  3. views/assignments/edit.php: Form for editing an existing assignment.
  4. views/assignments/show.php: View for displaying assignment details.
This setup provides a foundational structure for managing assignments within your Online Learning Platform. You can expand the functionality as needed based on your project requirements, such as adding features for submission tracking, grading, or additional metadata related to assignments.

controllers/QuizController.php
This controller will manage quizzes associated with modules, including listing quizzes, creating, updating, deleting quizzes, and viewing quiz details.

<?php
require_once 'models/Quiz.php';

class QuizController {
    // Display all quizzes for a specific module
    public function index($moduleId) {
        $quizzes = Quiz::getQuizzesByModuleId($moduleId);
        require_once 'views/quizzes/index.php'; // View for listing quizzes
    }

    // Display the form to create a new quiz
    public function create($moduleId) {
        require_once 'views/quizzes/create.php'; // View for quiz creation
    }

    // Handle quiz creation
    public function store($moduleId) {
        $title = $_POST['title'];
        $description = $_POST['description'];
        $duration = $_POST['duration']; // in minutes

        if (Quiz::createQuiz($moduleId, $title, $description, $duration)) {
            header("Location: index.php?action=quizzes&module_id=$moduleId"); // Redirect to quiz list
        } else {
            echo "Error creating quiz.";
        }
    }

    // Display the form to edit an existing quiz
    public function edit($quizId) {
        $quiz = Quiz::getQuizById($quizId);
        require_once 'views/quizzes/edit.php'; // View for quiz editing
    }

    // Handle quiz updates
    public function update($quizId) {
        $title = $_POST['title'];
        $description = $_POST['description'];
        $duration = $_POST['duration']; // in minutes

        if (Quiz::updateQuiz($quizId, $title, $description, $duration)) {
            // Get module ID for redirection
            $moduleId = Quiz::getModuleIdByQuizId($quizId);
            header("Location: index.php?action=quizzes&module_id=$moduleId"); // Redirect to quiz list
        } else {
            echo "Error updating quiz.";
        }
    }

    // Handle quiz deletion
    public function destroy($quizId) {
        $moduleId = Quiz::getModuleIdByQuizId($quizId); // Get module ID
        if (Quiz::deleteQuiz($quizId)) {
            header("Location: index.php?action=quizzes&module_id=$moduleId"); // Redirect to quiz list
        } else {
            echo "Error deleting quiz.";
        }
    }

    // Display quiz details
    public function show($quizId) {
        $quiz = Quiz::getQuizById($quizId);
        require_once 'views/quizzes/show.php'; // View for quiz details
    }
}
Explanation of QuizController.php
  1. Index Method: Retrieves all quizzes for a specific module and displays them using the index view.
  2. Create Method: Displays the form for creating a new quiz associated with a specific module.
  3. Store Method: Handles the form submission for creating a new quiz. It retrieves the quiz title, description, and duration, and calls the model method to save it to the database.
  4. Edit Method: Retrieves the quiz details by ID and displays the edit form.
  5. Update Method: Handles the form submission for updating an existing quiz. It updates the quiz details in the database and redirects to the quiz list.
  6. Destroy Method: Deletes the specified quiz and redirects to the quiz list.
  7. Show Method: Displays the details of a specific quiz.
Integration
You will need to set up routing in your application to connect actions to this controller. Here’s an example routing mechanism in index.php:

if (isset($_GET['action'])) {
    $action = $_GET['action'];

    switch ($action) {
        // Other cases...

        case 'quizzes':
            $controller = new QuizController();
            $controller->index($_GET['module_id']);
            break;
        case 'create_quiz':
            $controller = new QuizController();
            $controller->create($_GET['module_id']);
            break;
        case 'store_quiz':
            $controller = new QuizController();
            $controller->store($_GET['module_id']);
            break;
        case 'edit_quiz':
            $controller = new QuizController();
            $controller->edit($_GET['quiz_id']);
            break;
        case 'update_quiz':
            $controller = new QuizController();
            $controller->update($_GET['quiz_id']);
            break;
        case 'delete_quiz':
            $controller = new QuizController();
            $controller->destroy($_GET['quiz_id']);
            break;
        case 'show_quiz':
            $controller = new QuizController();
            $controller->show($_GET['quiz_id']);
            break;
        default:
            // Handle 404
            break;
    }
}
Views
Make sure to create the necessary views:

  1. views/quizzes/index.php: List of quizzes for a specific module.
  2. views/quizzes/create.php: Form for creating a new quiz.
  3. views/quizzes/edit.php: Form for editing an existing quiz.
  4. views/quizzes/show.php: View for displaying quiz details.
Expansion
You can expand the quiz functionality to include additional features, such as:

Adding questions to quizzes (create a separate QuestionController.php).
Tracking student performance on quizzes.
Setting quiz attempts and deadlines.
Displaying quiz results and feedback.
This setup provides a foundational structure for managing quizzes within your Online Learning Platform. Feel free to customize and expand upon this as per your project requirements.


controllers/SubmissionController.php
This controller will manage student submissions for assignments, quizzes, or any other evaluative content. It will handle creating, updating, deleting, and listing submissions.

<?php
require_once 'models/Submission.php';

class SubmissionController {
    // Display all submissions for a specific assignment or quiz
    public function index($courseId) {
        $submissions = Submission::getSubmissionsByCourseId($courseId);
        require_once 'views/submissions/index.php';
    }

    // Show the form to create a new submission
    public function create($courseId) {
        require_once 'views/submissions/create.php';
    }

    // Store a new submission in the database
    public function store($courseId) {
        $studentId = $_POST['student_id'];
        $file = $_FILES['submission_file'];

        // Check if file is uploaded without errors
        if ($file['error'] === UPLOAD_ERR_OK) {
            $fileName = basename($file['name']);
            $uploadDir = 'uploads/submissions/';
            $uploadFile = $uploadDir . $fileName;

            // Move uploaded file to the specified directory
            if (move_uploaded_file($file['tmp_name'], $uploadFile)) {
                if (Submission::createSubmission($courseId, $studentId, $uploadFile)) {
                    header('Location: index.php?action=submissions&course_id=' . $courseId); // Redirect to submissions index
                } else {
                    echo "Error creating submission.";
                }
            } else {
                echo "Error moving uploaded file.";
            }
        } else {
            echo "Error uploading file.";
        }
    }

    // Show the form to edit an existing submission
    public function edit($id) {
        $submission = Submission::getSubmissionById($id);
        require_once 'views/submissions/edit.php';
    }

    // Update the submission in the database
    public function update($id) {
        $studentId = $_POST['student_id'];
        $file = $_FILES['submission_file'];

        // Handle file upload
        if ($file['error'] === UPLOAD_ERR_OK) {
            $fileName = basename($file['name']);
            $uploadDir = 'uploads/submissions/';
            $uploadFile = $uploadDir . $fileName;

            // Move uploaded file to the specified directory
            if (move_uploaded_file($file['tmp_name'], $uploadFile)) {
                if (Submission::updateSubmission($id, $studentId, $uploadFile)) {
                    header('Location: index.php?action=submissions&course_id=' . $_POST['course_id']); // Redirect to submissions index
                } else {
                    echo "Error updating submission.";
                }
            } else {
                echo "Error moving uploaded file.";
            }
        } else {
            echo "Error uploading file.";
        }
    }

    // Delete a submission
    public function destroy($id) {
        if (Submission::deleteSubmission($id)) {
            header('Location: index.php?action=submissions&course_id=' . $_GET['course_id']); // Redirect to submissions index
        } else {
            echo "Error deleting submission.";
        }
    }
}
Explanation of SubmissionController.php
  1. Index Method: Retrieves all submissions for a specific course and displays them in a view.
  2. Create Method: Displays the form for creating a new submission.
  3. Store Method: Processes the submission form to store a new submission in the database. It handles file uploads, checks for upload errors, and saves the file to a specified directory. If successful, it redirects to the submissions index page.
  4. Edit Method: Retrieves a specific submission by its ID and displays it in the edit form.
  5. Update Method: Processes the form submission for updating a submission. Similar to the store method, it handles file uploads and updates the submission in the database. It redirects to the submissions index page upon success.
  6. Destroy Method: Deletes a submission by its ID and redirects to the submissions index page.
Integration
You will need to set up routing in your application to connect actions to this controller. Here’s an example routing mechanism in index.php:

if (isset($_GET['action'])) {
    $action = $_GET['action'];

    switch ($action) {
        // Other cases...
        
        case 'submissions':
            $controller = new SubmissionController();
            $controller->index($_GET['course_id']);
            break;
        case 'create_submission':
            $controller = new SubmissionController();
            $controller->create($_GET['course_id']);
            break;
        case 'store_submission':
            $controller = new SubmissionController();
            $controller->store($_GET['course_id']);
            break;
        case 'edit_submission':
            $controller = new SubmissionController();
            $controller->edit($_GET['id']);
            break;
        case 'update_submission':
            $controller = new SubmissionController();
            $controller->update($_GET['id']);
            break;
        case 'delete_submission':
            $controller = new SubmissionController();
            $controller->destroy($_GET['id']);
            break;
        default:
            // Handle 404
            break;
    }
}
This setup allows you to manage student submissions effectively within your Online Learning Platform.


controllers/NotificationController.php
This controller will manage notifications for users, such as assignment updates, course announcements, or system messages.

<?php
require_once 'models/Notification.php';

class NotificationController {
    // Display all notifications for a specific user
    public function index($userId) {
        $notifications = Notification::getNotificationsByUserId($userId);
        require_once 'views/notifications/index.php';
    }

    // Show the form to create a new notification
    public function create() {
        require_once 'views/notifications/create.php';
    }

    // Store a new notification in the database
    public function store() {
        $title = $_POST['title'];
        $message = $_POST['message'];
        $userId = $_POST['user_id']; // assuming notifications are sent to a specific user

        if (Notification::createNotification($title, $message, $userId)) {
            header('Location: index.php?action=notifications&user_id=' . $userId); // Redirect to notifications index
        } else {
            echo "Error creating notification.";
        }
    }

    // Show the form to edit an existing notification
    public function edit($id) {
        $notification = Notification::getNotificationById($id);
        require_once 'views/notifications/edit.php';
    }

    // Update the notification in the database
    public function update($id) {
        $title = $_POST['title'];
        $message = $_POST['message'];

        if (Notification::updateNotification($id, $title, $message)) {
            header('Location: index.php?action=notifications&user_id=' . $_POST['user_id']); // Redirect to notifications index
        } else {
            echo "Error updating notification.";
        }
    }

    // Delete a notification
    public function destroy($id) {
        if (Notification::deleteNotification($id)) {
            header('Location: index.php?action=notifications&user_id=' . $_GET['user_id']); // Redirect to notifications index
        } else {
            echo "Error deleting notification.";
        }
    }
}
Explanation of NotificationController.php
  1. Index Method: Retrieves all notifications for a specific user and displays them in a view.
  2. Create Method: Displays the form for creating a new notification.
  3. Store Method: Processes the notification form to store a new notification in the database. It retrieves the title, message, and user ID from the form and calls the model to save the notification. If successful, it redirects to the notifications index page.
  4. Edit Method: Retrieves a specific notification by its ID and displays it in the edit form.
  5. Update Method: Processes the form submission for updating a notification. It retrieves the updated title and message and updates the notification in the database. It redirects to the notifications index page upon success.
  6. Destroy Method: Deletes a notification by its ID and redirects to the notifications index page.
Integration
You will need to set up routing in your application to connect actions to this controller. Here’s an example routing mechanism in index.php:
if (isset($_GET['action'])) {
    $action = $_GET['action'];

    switch ($action) {
        // Other cases...
        
        case 'notifications':
            $controller = new NotificationController();
            $controller->index($_GET['user_id']);
            break;
        case 'create_notification':
            $controller = new NotificationController();
            $controller->create();
            break;
        case 'store_notification':
            $controller = new NotificationController();
            $controller->store();
            break;
        case 'edit_notification':
            $controller = new NotificationController();
            $controller->edit($_GET['id']);
            break;
        case 'update_notification':
            $controller = new NotificationController();
            $controller->update($_GET['id']);
            break;
        case 'delete_notification':
            $controller = new NotificationController();
            $controller->destroy($_GET['id']);
            break;
        default:
            // Handle 404
            break;
    }
}
This setup allows you to manage notifications effectively within your Online Learning Platform, keeping users informed about important updates and announcements. You can further expand the functionality as needed based on your project's requirements.


controllers/UserController.php
UserController.php controller will handle user-related functionalities, including user registration, login, profile management, and user role management (admin, instructor, student).

<?php
require_once 'models/User.php';

class UserController {
    // Display the user login form
    public function login() {
        require_once 'views/users/login.php';
    }

    // Handle user login logic
    public function loginUser() {
        $email = $_POST['email'];
        $password = $_POST['password'];

        $user = User::getUserByEmail($email);
        
        if ($user && password_verify($password, $user['password'])) {
            // Set session variables
            session_start();
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['role'] = $user['role'];

            header('Location: index.php?action=dashboard'); // Redirect to dashboard
        } else {
            echo "Invalid email or password.";
        }
    }

    // Display the registration form
    public function register() {
        require_once 'views/users/register.php';
    }

    // Handle user registration logic
    public function registerUser() {
        $name = $_POST['name'];
        $email = $_POST['email'];
        $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
        $role = 'student'; // Default role can be modified as needed

        if (User::createUser($name, $email, $password, $role)) {
            header('Location: index.php?action=login'); // Redirect to login
        } else {
            echo "Error registering user.";
        }
    }

    // Display the user profile
    public function profile($userId) {
        $user = User::getUserById($userId);
        require_once 'views/users/profile.php';
    }

    // Update user profile information
    public function updateProfile($userId) {
        $name = $_POST['name'];
        $email = $_POST['email'];

        if (User::updateUser($userId, $name, $email)) {
            header('Location: index.php?action=profile&user_id=' . $userId); // Redirect to profile
        } else {
            echo "Error updating profile.";
        }
    }

    // Logout user
    public function logout() {
        session_start();
        session_destroy();
        header('Location: index.php?action=login'); // Redirect to login
    }
}
Explanation of UserController.php
  1. Login Method: Displays the user login form.
  2. LoginUser Method: Processes the login form. It retrieves the user by email and verifies the password. If successful, it sets session variables and redirects to the dashboard.
  3. Register Method: Displays the user registration form.
  4. RegisterUser Method: Handles the registration logic. It hashes the password and creates a new user in the database. Upon success, it redirects to the login page.
  5. Profile Method: Displays the user profile information for the specified user ID.
  6. UpdateProfile Method: Processes the form submission for updating user profile information. It retrieves the updated name and email and updates the user in the database. It redirects to the profile page upon success.
  7. Logout Method: Destroys the session, effectively logging out the user, and redirects to the login page.
Integration
You will need to set up routing in your application to connect actions to this controller. Here’s an example routing mechanism in index.php:

if (isset($_GET['action'])) {
    $action = $_GET['action'];

    switch ($action) {
        // Other cases...

        case 'login':
            $controller = new UserController();
            $controller->login();
            break;
        case 'login_user':
            $controller = new UserController();
            $controller->loginUser();
            break;
        case 'register':
            $controller = new UserController();
            $controller->register();
            break;
        case 'register_user':
            $controller = new UserController();
            $controller->registerUser();
            break;
        case 'profile':
            $controller = new UserController();
            $controller->profile($_GET['user_id']);
            break;
        case 'update_profile':
            $controller = new UserController();
            $controller->updateProfile($_GET['user_id']);
            break;
        case 'logout':
            $controller = new UserController();
            $controller->logout();
            break;
        default:
            // Handle 404
            break;
    }
}
This setup allows you to manage user-related functionalities effectively within your Online Learning Platform, ensuring a seamless user experience for registration, login, profile management, and logout. You can further expand the functionality as needed based on your project's requirements.





3. Models

1.models/User.php

 This model will handle user-related operations such as user registration, authentication, fetching user data, and updating user information.

<?php
class User {
    private $db;

    public function __construct($database) {
        $this->db = $database; // Assume $database is a PDO instance
    }

    // User registration
    public static function register($name, $email, $password) {
        global $db;

        $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
        $query = "INSERT INTO users (name, email, password, role, created_at, updated_at) VALUES (:name, :email, :password, 'student', NOW(), NOW())";
        $stmt = $db->prepare($query);
        $stmt->bindParam(':name', $name);
        $stmt->bindParam(':email', $email);
        $stmt->bindParam(':password', $hashedPassword);

        return $stmt->execute();
    }

    // User authentication
    public static function authenticate($email, $password) {
        global $db;

        $query = "SELECT * FROM users WHERE email = :email LIMIT 1";
        $stmt = $db->prepare($query);
        $stmt->bindParam(':email', $email);
        $stmt->execute();

        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($user && password_verify($password, $user['password'])) {
            return $user; // Return user data if authentication is successful
        }

        return false; // Authentication failed
    }

    // Get user by ID
    public static function getUserById($userId) {
        global $db;

        $query = "SELECT * FROM users WHERE id = :id LIMIT 1";
        $stmt = $db->prepare($query);
        $stmt->bindParam(':id', $userId);
        $stmt->execute();

        return $stmt->fetch(PDO::FETCH_ASSOC);
    }

    // Update user information
    public static function updateUser($userId, $name, $email, $password = null) {
        global $db;

        $query = "UPDATE users SET name = :name, email = :email, updated_at = NOW() WHERE id = :id";
        if ($password) {
            $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
            $query = "UPDATE users SET name = :name, email = :email, password = :password, updated_at = NOW() WHERE id = :id";
        }

        $stmt = $db->prepare($query);
        $stmt->bindParam(':name', $name);
        $stmt->bindParam(':email', $email);
        $stmt->bindParam(':id', $userId);

        if ($password) {
            $stmt->bindParam(':password', $hashedPassword);
        }

        return $stmt->execute();
    }

    // Get all users (Admin feature)
    public static function getAllUsers() {
        global $db;

        $query = "SELECT * FROM users";
        $stmt = $db->prepare($query);
        $stmt->execute();

        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    // Delete user
    public static function deleteUser($userId) {
        global $db;

        $query = "DELETE FROM users WHERE id = :id";
        $stmt = $db->prepare($query);
        $stmt->bindParam(':id', $userId);

        return $stmt->execute();
    }
}
Explanation of User.php
  1. Constructor: Accepts a database connection (assumed to be a PDO instance) for database operations.
  2. Register Method: Takes user details (name, email, and password), hashes the password, and inserts the new user into the users table. The role is set to 'student' by default.
  3. Authenticate Method: Checks if the user exists by email and verifies the password. Returns the user data if authentication is successful.
  4. Get User By ID Method: Fetches user details based on the user ID.
  5. Update User Method: Updates user information. If a new password is provided, it will update that as well.
  6. Get All Users Method: Retrieves all users from the database (this can be used by an admin to view all users).
  7. Delete User Method: Deletes a user based on the user ID.
Integration
You can use this model within your controllers. For example, during user registration or login in the AuthController.php, you would call methods from the User model to manage user data.

Example Usage in AuthController.php
// In AuthController.php

public function register() {
    // Get form data
    $name = $_POST['name'];
    $email = $_POST['email'];
    $password = $_POST['password'];

    if (User::register($name, $email, $password)) {
        header("Location: login.php"); // Redirect to login page
    } else {
        echo "Error registering user.";
    }
}

public function login() {
    // Get form data
    $email = $_POST['email'];
    $password = $_POST['password'];

    $user = User::authenticate($email, $password);
    if ($user) {
        // Set session variables
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['user_name'] = $user['name'];
        header("Location: dashboard.php"); // Redirect to user dashboard
    } else {
        echo "Invalid email or password.";
    }
}
This User.php model provides a foundational structure for managing user-related functionality in your Online Learning Platform. You can expand upon this by adding more specific methods as needed for your project.

2. models/Course.php
This model handles all operations related to courses, including creating, fetching, updating, and deleting courses.
<?php
class Course {
    private $db;

    public function __construct($database) {
        $this->db = $database; // Assume $database is a PDO instance
    }

    // Create a new course
    public function createCourse($title, $description, $instructorId, $createdAt) {
        $query = "INSERT INTO courses (title, description, instructor_id, created_at, updated_at) 
                  VALUES (:title, :description, :instructor_id, :created_at, NOW())";

        $stmt = $this->db->prepare($query);
        $stmt->bindParam(':title', $title);
        $stmt->bindParam(':description', $description);
        $stmt->bindParam(':instructor_id', $instructorId);
        $stmt->bindParam(':created_at', $createdAt);

        return $stmt->execute();
    }

    // Get all courses
    public function getAllCourses() {
        $query = "SELECT * FROM courses";
        $stmt = $this->db->prepare($query);
        $stmt->execute();

        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    // Get course by ID
    public function getCourseById($courseId) {
        $query = "SELECT * FROM courses WHERE id = :id LIMIT 1";
        $stmt = $this->db->prepare($query);
        $stmt->bindParam(':id', $courseId);
        $stmt->execute();

        return $stmt->fetch(PDO::FETCH_ASSOC);
    }

    // Update course
    public function updateCourse($courseId, $title, $description) {
        $query = "UPDATE courses SET title = :title, description = :description, updated_at = NOW() WHERE id = :id";
        $stmt = $this->db->prepare($query);
        $stmt->bindParam(':title', $title);
        $stmt->bindParam(':description', $description);
        $stmt->bindParam(':id', $courseId);

        return $stmt->execute();
    }

    // Delete course
    public function deleteCourse($courseId) {
        $query = "DELETE FROM courses WHERE id = :id";
        $stmt = $this->db->prepare($query);
        $stmt->bindParam(':id', $courseId);

        return $stmt->execute();
    }

    // Get courses by instructor ID
    public function getCoursesByInstructor($instructorId) {
        $query = "SELECT * FROM courses WHERE instructor_id = :instructor_id";
        $stmt = $this->db->prepare($query);
        $stmt->bindParam(':instructor_id', $instructorId);
        $stmt->execute();

        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
}
Explanation of Course.php
  1. Constructor: Accepts a database connection (assumed to be a PDO instance) for database operations.
  2. Create Course Method: Takes course details (title, description, instructor ID, and creation date) and inserts a new course into the courses table.
  3. Get All Courses Method: Fetches all courses from the database.
  4. Get Course By ID Method: Fetches a course's details based on the course ID.
  5. Update Course Method: Updates a course's title and description based on the course ID.
  6. Delete Course Method: Deletes a course based on the course ID.
  7. Get Courses By Instructor Method: Fetches all courses assigned to a specific instructor.
Integration
You can use this model within your controllers. For example, in a CourseController.php, you can manage course creation, updates, and deletions by calling methods from the Course model.

Example Usage in CourseController.php
// In CourseController.php

public function create() {
    // Get form data
    $title = $_POST['title'];
    $description = $_POST['description'];
    $instructorId = $_POST['instructor_id'];
    $createdAt = date('Y-m-d H:i:s');

    if (Course::createCourse($title, $description, $instructorId, $createdAt)) {
        header("Location: courses.php"); // Redirect to courses page
    } else {
        echo "Error creating course.";
    }
}

public function update($courseId) {
    // Get form data
    $title = $_POST['title'];
    $description = $_POST['description'];

    if (Course::updateCourse($courseId, $title, $description)) {
        header("Location: course.php?id=" . $courseId); // Redirect to course details page
    } else {
        echo "Error updating course.";
    }
}

public function delete($courseId) {
    if (Course::deleteCourse($courseId)) {
        header("Location: courses.php"); // Redirect to courses page
    } else {
        echo "Error deleting course.";
    }
}
This Course.php model provides a foundational structure for managing course-related functionality in your Online Learning Platform. You can expand upon this by adding more specific methods or features as needed for your project.


3.models/Module.php
This model handles all operations related to modules within a course, including creating, fetching, updating, and deleting modules.
<?php
class Module {
    private $db;

    public function __construct($database) {
        $this->db = $database; // Assume $database is a PDO instance
    }

    // Create a new module
    public function createModule($courseId, $title, $description, $createdAt) {
        $query = "INSERT INTO modules (course_id, title, description, created_at, updated_at) 
                  VALUES (:course_id, :title, :description, :created_at, NOW())";

        $stmt = $this->db->prepare($query);
        $stmt->bindParam(':course_id', $courseId);
        $stmt->bindParam(':title', $title);
        $stmt->bindParam(':description', $description);
        $stmt->bindParam(':created_at', $createdAt);

        return $stmt->execute();
    }

    // Get all modules for a specific course
    public function getModulesByCourseId($courseId) {
        $query = "SELECT * FROM modules WHERE course_id = :course_id";
        $stmt = $this->db->prepare($query);
        $stmt->bindParam(':course_id', $courseId);
        $stmt->execute();

        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    // Get module by ID
    public function getModuleById($moduleId) {
        $query = "SELECT * FROM modules WHERE id = :id LIMIT 1";
        $stmt = $this->db->prepare($query);
        $stmt->bindParam(':id', $moduleId);
        $stmt->execute();

        return $stmt->fetch(PDO::FETCH_ASSOC);
    }

    // Update module
    public function updateModule($moduleId, $title, $description) {
        $query = "UPDATE modules SET title = :title, description = :description, updated_at = NOW() WHERE id = :id";
        $stmt = $this->db->prepare($query);
        $stmt->bindParam(':title', $title);
        $stmt->bindParam(':description', $description);
        $stmt->bindParam(':id', $moduleId);

        return $stmt->execute();
    }

    // Delete module
    public function deleteModule($moduleId) {
        $query = "DELETE FROM modules WHERE id = :id";
        $stmt = $this->db->prepare($query);
        $stmt->bindParam(':id', $moduleId);

        return $stmt->execute();
    }
}
Explanation of Module.php
  1. Constructor: Accepts a database connection (assumed to be a PDO instance) for database operations.
  2. Create Module Method: Takes module details (course ID, title, description, and creation date) and inserts a new module into the modules table.
  3. Get Modules By Course ID Method: Fetches all modules associated with a specific course based on the course ID.
  4. Get Module By ID Method: Fetches the details of a specific module based on the module ID.
  5. Update Module Method: Updates a module's title and description based on the module ID.
  6. Delete Module Method: Deletes a module based on the module ID.
Integration
You can use this model within your controllers, such as ModuleController.php, to manage module-related actions.

Example Usage in ModuleController.php
// In ModuleController.php

public function create() {
    // Get form data
    $courseId = $_POST['course_id'];
    $title = $_POST['title'];
    $description = $_POST['description'];
    $createdAt = date('Y-m-d H:i:s');

    if (Module::createModule($courseId, $title, $description, $createdAt)) {
        header("Location: modules.php?course_id=" . $courseId); // Redirect to modules page
    } else {
        echo "Error creating module.";
    }
}

public function update($moduleId) {
    // Get form data
    $title = $_POST['title'];
    $description = $_POST['description'];

    if (Module::updateModule($moduleId, $title, $description)) {
        header("Location: module.php?id=" . $moduleId); // Redirect to module details page
    } else {
        echo "Error updating module.";
    }
}

public function delete($moduleId) {
    if (Module::deleteModule($moduleId)) {
        header("Location: modules.php"); // Redirect to modules page
    } else {
        echo "Error deleting module.";
    }
}
This Module.php model provides a foundational structure for managing module-related functionality in your Online Learning Platform. 


4.models/Assignment.php
This model handles all operations related to assignments within a course, including creating, fetching, updating, and deleting assignments.

<?php
class Assignment {
    private $db;

    public function __construct($database) {
        $this->db = $database; // Assume $database is a PDO instance
    }

    // Create a new assignment
    public function createAssignment($moduleId, $title, $description, $dueDate, $createdAt) {
        $query = "INSERT INTO assignments (module_id, title, description, due_date, created_at, updated_at) 
                  VALUES (:module_id, :title, :description, :due_date, :created_at, NOW())";

        $stmt = $this->db->prepare($query);
        $stmt->bindParam(':module_id', $moduleId);
        $stmt->bindParam(':title', $title);
        $stmt->bindParam(':description', $description);
        $stmt->bindParam(':due_date', $dueDate);
        $stmt->bindParam(':created_at', $createdAt);

        return $stmt->execute();
    }

    // Get all assignments for a specific module
    public function getAssignmentsByModuleId($moduleId) {
        $query = "SELECT * FROM assignments WHERE module_id = :module_id";
        $stmt = $this->db->prepare($query);
        $stmt->bindParam(':module_id', $moduleId);
        $stmt->execute();

        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    // Get assignment by ID
    public function getAssignmentById($assignmentId) {
        $query = "SELECT * FROM assignments WHERE id = :id LIMIT 1";
        $stmt = $this->db->prepare($query);
        $stmt->bindParam(':id', $assignmentId);
        $stmt->execute();

        return $stmt->fetch(PDO::FETCH_ASSOC);
    }

    // Update assignment
    public function updateAssignment($assignmentId, $title, $description, $dueDate) {
        $query = "UPDATE assignments SET title = :title, description = :description, due_date = :due_date, updated_at = NOW() WHERE id = :id";
        $stmt = $this->db->prepare($query);
        $stmt->bindParam(':title', $title);
        $stmt->bindParam(':description', $description);
        $stmt->bindParam(':due_date', $dueDate);
        $stmt->bindParam(':id', $assignmentId);

        return $stmt->execute();
    }

    // Delete assignment
    public function deleteAssignment($assignmentId) {
        $query = "DELETE FROM assignments WHERE id = :id";
        $stmt = $this->db->prepare($query);
        $stmt->bindParam(':id', $assignmentId);

        return $stmt->execute();
    }

    // Get assignments by due date
    public function getAssignmentsByDueDate($dueDate) {
        $query = "SELECT * FROM assignments WHERE due_date = :due_date";
        $stmt = $this->db->prepare($query);
        $stmt->bindParam(':due_date', $dueDate);
        $stmt->execute();

        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
}
Explanation of Assignment.php
  1. Constructor: Accepts a database connection (assumed to be a PDO instance) for database operations.
  2. Create Assignment Method: Takes assignment details (module ID, title, description, due date, and creation date) and inserts a new assignment into the assignments table.
  3. Get Assignments By Module ID Method: Fetches all assignments associated with a specific module based on the module ID.
  4. Get Assignment By ID Method: Fetches the details of a specific assignment based on the assignment ID.
  5. Update Assignment Method: Updates an assignment's title, description, and due date based on the assignment ID.
  6. Delete Assignment Method: Deletes an assignment based on the assignment ID.
  7. Get Assignments By Due Date Method: Fetches assignments that are due on a specific date.
Integration
You can use this model within your controllers, such as AssignmentController.php, to manage assignment-related actions.

Example Usage in AssignmentController.php
php
Copy code
// In AssignmentController.php

public function create() {
    // Get form data
    $moduleId = $_POST['module_id'];
    $title = $_POST['title'];
    $description = $_POST['description'];
    $dueDate = $_POST['due_date'];
    $createdAt = date('Y-m-d H:i:s');

    if (Assignment::createAssignment($moduleId, $title, $description, $dueDate, $createdAt)) {
        header("Location: assignments.php?module_id=" . $moduleId); // Redirect to assignments page
    } else {
        echo "Error creating assignment.";
    }
}

public function update($assignmentId) {
    // Get form data
    $title = $_POST['title'];
    $description = $_POST['description'];
    $dueDate = $_POST['due_date'];

    if (Assignment::updateAssignment($assignmentId, $title, $description, $dueDate)) {
        header("Location: assignment.php?id=" . $assignmentId); // Redirect to assignment details page
    } else {
        echo "Error updating assignment.";
    }
}

public function delete($assignmentId) {
    if (Assignment::deleteAssignment($assignmentId)) {
        header("Location: assignments.php"); // Redirect to assignments page
    } else {
        echo "Error deleting assignment.";
    }
}
This Assignment.php model provides a foundational structure for managing assignment-related functionality in your Online Learning Platform. You can expand this model further based on your project’s requirements.

5.models/Quiz.php
This model handles all operations related to quizzes within a course, including creating, fetching, updating, and deleting quizzes, as well as managing questions related to each quiz.
<?php
class Quiz {
    private $db;

    public function __construct($database) {
        $this->db = $database; // Assume $database is a PDO instance
    }

    // Create a new quiz
    public function createQuiz($moduleId, $title, $description, $createdAt) {
        $query = "INSERT INTO quizzes (module_id, title, description, created_at, updated_at) 
                  VALUES (:module_id, :title, :description, :created_at, NOW())";

        $stmt = $this->db->prepare($query);
        $stmt->bindParam(':module_id', $moduleId);
        $stmt->bindParam(':title', $title);
        $stmt->bindParam(':description', $description);
        $stmt->bindParam(':created_at', $createdAt);

        return $stmt->execute();
    }

    // Get all quizzes for a specific module
    public function getQuizzesByModuleId($moduleId) {
        $query = "SELECT * FROM quizzes WHERE module_id = :module_id";
        $stmt = $this->db->prepare($query);
        $stmt->bindParam(':module_id', $moduleId);
        $stmt->execute();

        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    // Get quiz by ID
    public function getQuizById($quizId) {
        $query = "SELECT * FROM quizzes WHERE id = :id LIMIT 1";
        $stmt = $this->db->prepare($query);
        $stmt->bindParam(':id', $quizId);
        $stmt->execute();

        return $stmt->fetch(PDO::FETCH_ASSOC);
    }

    // Update quiz
    public function updateQuiz($quizId, $title, $description) {
        $query = "UPDATE quizzes SET title = :title, description = :description, updated_at = NOW() WHERE id = :id";
        $stmt = $this->db->prepare($query);
        $stmt->bindParam(':title', $title);
        $stmt->bindParam(':description', $description);
        $stmt->bindParam(':id', $quizId);

        return $stmt->execute();
    }

    // Delete quiz
    public function deleteQuiz($quizId) {
        $query = "DELETE FROM quizzes WHERE id = :id";
        $stmt = $this->db->prepare($query);
        $stmt->bindParam(':id', $quizId);

        return $stmt->execute();
    }

    // Create a new question for a quiz
    public function createQuestion($quizId, $questionText, $optionA, $optionB, $optionC, $optionD, $correctOption) {
        $query = "INSERT INTO quiz_questions (quiz_id, question_text, option_a, option_b, option_c, option_d, correct_option) 
                  VALUES (:quiz_id, :question_text, :option_a, :option_b, :option_c, :option_d, :correct_option)";

        $stmt = $this->db->prepare($query);
        $stmt->bindParam(':quiz_id', $quizId);
        $stmt->bindParam(':question_text', $questionText);
        $stmt->bindParam(':option_a', $optionA);
        $stmt->bindParam(':option_b', $optionB);
        $stmt->bindParam(':option_c', $optionC);
        $stmt->bindParam(':option_d', $optionD);
        $stmt->bindParam(':correct_option', $correctOption);

        return $stmt->execute();
    }

    // Get all questions for a specific quiz
    public function getQuestionsByQuizId($quizId) {
        $query = "SELECT * FROM quiz_questions WHERE quiz_id = :quiz_id";
        $stmt = $this->db->prepare($query);
        $stmt->bindParam(':quiz_id', $quizId);
        $stmt->execute();

        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    // Delete question
    public function deleteQuestion($questionId) {
        $query = "DELETE FROM quiz_questions WHERE id = :id";
        $stmt = $this->db->prepare($query);
        $stmt->bindParam(':id', $questionId);

        return $stmt->execute();
    }
}
Explanation of Quiz.php
  1. Constructor: Accepts a database connection (assumed to be a PDO instance) for database operations.
  2. Create Quiz Method: Takes quiz details (module ID, title, description, and creation date) and inserts a new quiz into the quizzes table.
  3. Get Quizzes By Module ID Method: Fetches all quizzes associated with a specific module based on the module ID.
  4. Get Quiz By ID Method: Fetches the details of a specific quiz based on the quiz ID.
  5. Update Quiz Method: Updates a quiz's title and description based on the quiz ID.
  6. Delete Quiz Method: Deletes a quiz based on the quiz ID.
  7. Create Question Method: Inserts a new question for a quiz, including options and the correct answer.
  8. Get Questions By Quiz ID Method: Fetches all questions associated with a specific quiz.
  9. Delete Question Method: Deletes a question based on the question ID.
Integration
You can use this model within your controllers, such as QuizController.php, to manage quiz-related actions.

Example Usage in QuizController.php
// In QuizController.php

public function create() {
    // Get form data
    $moduleId = $_POST['module_id'];
    $title = $_POST['title'];
    $description = $_POST['description'];
    $createdAt = date('Y-m-d H:i:s');

    if (Quiz::createQuiz($moduleId, $title, $description, $createdAt)) {
        header("Location: quizzes.php?module_id=" . $moduleId); // Redirect to quizzes page
    } else {
        echo "Error creating quiz.";
    }
}

public function update($quizId) {
    // Get form data
    $title = $_POST['title'];
    $description = $_POST['description'];

    if (Quiz::updateQuiz($quizId, $title, $description)) {
        header("Location: quiz.php?id=" . $quizId); // Redirect to quiz details page
    } else {
        echo "Error updating quiz.";
    }
}

public function delete($quizId) {
    if (Quiz::deleteQuiz($quizId)) {
        header("Location: quizzes.php"); // Redirect to quizzes page
    } else {
        echo "Error deleting quiz.";
    }
}

public function createQuestion($quizId) {
    // Get question data
    $questionText = $_POST['question_text'];
    $optionA = $_POST['option_a'];
    $optionB = $_POST['option_b'];
    $optionC = $_POST['option_c'];
    $optionD = $_POST['option_d'];
    $correctOption = $_POST['correct_option'];

    if (Quiz::createQuestion($quizId, $questionText, $optionA, $optionB, $optionC, $optionD, $correctOption)) {
        header("Location: quiz.php?id=" . $quizId); // Redirect to quiz details page
    } else {
        echo "Error creating question.";
    }
}

public function deleteQuestion($questionId) {
    if (Quiz::deleteQuestion($questionId)) {
        header("Location: quiz.php?id=" . $quizId); // Redirect to quiz details page
    } else {
        echo "Error deleting question.";
    }
}
This Quiz.php model provides a foundational structure for managing quiz-related functionality in your Online Learning Platform. 


6. models/Submission.php
<?php
class Submission {
    private $db;

    public function __construct($database) {
        $this->db = $database; // Assume $database is a PDO instance
    }

    // Create a new submission
    public function createSubmission($userId, $assignmentId, $submissionContent, $submittedAt) {
        $query = "INSERT INTO submissions (user_id, assignment_id, submission_content, submitted_at, updated_at) 
                  VALUES (:user_id, :assignment_id, :submission_content, :submitted_at, NOW())";

        $stmt = $this->db->prepare($query);
        $stmt->bindParam(':user_id', $userId);
        $stmt->bindParam(':assignment_id', $assignmentId);
        $stmt->bindParam(':submission_content', $submissionContent);
        $stmt->bindParam(':submitted_at', $submittedAt);

        return $stmt->execute();
    }

    // Get all submissions for a specific assignment
    public function getSubmissionsByAssignmentId($assignmentId) {
        $query = "SELECT * FROM submissions WHERE assignment_id = :assignment_id";
        $stmt = $this->db->prepare($query);
        $stmt->bindParam(':assignment_id', $assignmentId);
        $stmt->execute();

        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    // Get submission by ID
    public function getSubmissionById($submissionId) {
        $query = "SELECT * FROM submissions WHERE id = :id LIMIT 1";
        $stmt = $this->db->prepare($query);
        $stmt->bindParam(':id', $submissionId);
        $stmt->execute();

        return $stmt->fetch(PDO::FETCH_ASSOC);
    }

    // Update submission
    public function updateSubmission($submissionId, $submissionContent) {
        $query = "UPDATE submissions SET submission_content = :submission_content, updated_at = NOW() WHERE id = :id";
        $stmt = $this->db->prepare($query);
        $stmt->bindParam(':submission_content', $submissionContent);
        $stmt->bindParam(':id', $submissionId);

        return $stmt->execute();
    }

    // Delete submission
    public function deleteSubmission($submissionId) {
        $query = "DELETE FROM submissions WHERE id = :id";
        $stmt = $this->db->prepare($query);
        $stmt->bindParam(':id', $submissionId);

        return $stmt->execute();
    }

    // Get submissions by user ID
    public function getSubmissionsByUserId($userId) {
        $query = "SELECT * FROM submissions WHERE user_id = :user_id";
        $stmt = $this->db->prepare($query);
        $stmt->bindParam(':user_id', $userId);
        $stmt->execute();

        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
}
Explanation of Submission.php
  1. Constructor: Accepts a database connection (assumed to be a PDO instance) for database operations.
  2. Create Submission Method: Takes details about the user, assignment ID, submission content, and submission time, and inserts a new submission into the submissions table.
  3. Get Submissions By Assignment ID Method: Fetches all submissions associated with a specific assignment based on the assignment ID.
  4. Get Submission By ID Method: Fetches the details of a specific submission based on the submission ID.
  5. Update Submission Method: Updates a submission's content based on the submission ID.
  6. Delete Submission Method: Deletes a submission based on the submission ID.
  7. Get Submissions By User ID Method: Fetches all submissions made by a specific user based on the user ID.
Integration
You can use this model within your controllers, such as SubmissionController.php, to manage submission-related actions.

Example Usage in SubmissionController.php
// In SubmissionController.php

public function create() {
    // Get form data
    $userId = $_SESSION['user_id']; // Assume user ID is stored in session
    $assignmentId = $_POST['assignment_id'];
    $submissionContent = $_POST['submission_content'];
    $submittedAt = date('Y-m-d H:i:s');

    if (Submission::createSubmission($userId, $assignmentId, $submissionContent, $submittedAt)) {
        header("Location: submissions.php?assignment_id=" . $assignmentId); // Redirect to submissions page
    } else {
        echo "Error creating submission.";
    }
}

public function update($submissionId) {
    // Get form data
    $submissionContent = $_POST['submission_content'];

    if (Submission::updateSubmission($submissionId, $submissionContent)) {
        header("Location: submission.php?id=" . $submissionId); // Redirect to submission details page
    } else {
        echo "Error updating submission.";
    }
}

public function delete($submissionId) {
    if (Submission::deleteSubmission($submissionId)) {
        header("Location: submissions.php"); // Redirect to submissions page
    } else {
        echo "Error deleting submission.";
    }
}

public function getUserSubmissions($userId) {
    $submissions = Submission::getSubmissionsByUserId($userId);
    // Process and display submissions as needed
}
This Submission.php model provides a foundational structure for managing assignment and quiz submissions in your Online Learning Platform. 
7. models/Notification.php
<?php
class Notification {
    private $db;

    public function __construct($database) {
        $this->db = $database; // Assume $database is a PDO instance
    }

    // Create a new notification
    public function createNotification($userId, $message, $notificationType, $createdAt) {
        $query = "INSERT INTO notifications (user_id, message, notification_type, created_at) 
                  VALUES (:user_id, :message, :notification_type, :created_at)";

        $stmt = $this->db->prepare($query);
        $stmt->bindParam(':user_id', $userId);
        $stmt->bindParam(':message', $message);
        $stmt->bindParam(':notification_type', $notificationType);
        $stmt->bindParam(':created_at', $createdAt);

        return $stmt->execute();
    }

    // Get all notifications for a specific user
    public function getNotificationsByUserId($userId) {
        $query = "SELECT * FROM notifications WHERE user_id = :user_id ORDER BY created_at DESC";
        $stmt = $this->db->prepare($query);
        $stmt->bindParam(':user_id', $userId);
        $stmt->execute();

        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    // Get notification by ID
    public function getNotificationById($notificationId) {
        $query = "SELECT * FROM notifications WHERE id = :id LIMIT 1";
        $stmt = $this->db->prepare($query);
        $stmt->bindParam(':id', $notificationId);
        $stmt->execute();

        return $stmt->fetch(PDO::FETCH_ASSOC);
    }

    // Mark notification as read
    public function markAsRead($notificationId) {
        $query = "UPDATE notifications SET is_read = 1 WHERE id = :id";
        $stmt = $this->db->prepare($query);
        $stmt->bindParam(':id', $notificationId);

        return $stmt->execute();
    }

    // Delete notification
    public function deleteNotification($notificationId) {
        $query = "DELETE FROM notifications WHERE id = :id";
        $stmt = $this->db->prepare($query);
        $stmt->bindParam(':id', $notificationId);

        return $stmt->execute();
    }
}
Explanation of Notification.php
  1. Constructor: Accepts a database connection (assumed to be a PDO instance) for database operations.
  2. Create Notification Method: Takes details about the user, notification message, type, and creation time, and inserts a new notification into the notifications table.
  3. Get Notifications By User ID Method: Fetches all notifications associated with a specific user based on the user ID and orders them by creation time (most recent first).
  4. Get Notification By ID Method: Fetches the details of a specific notification based on the notification ID.
  5. Mark As Read Method: Updates a notification to mark it as read based on the notification ID.
  6. Delete Notification Method: Deletes a notification based on the notification ID.
Integration
You can use this model within your controllers, such as NotificationController.php, to manage notification-related actions.

Example Usage in NotificationController.php
// In NotificationController.php

public function create($userId, $message, $notificationType) {
    $createdAt = date('Y-m-d H:i:s');

    if (Notification::createNotification($userId, $message, $notificationType, $createdAt)) {
        echo "Notification created successfully.";
    } else {
        echo "Error creating notification.";
    }
}

public function getUserNotifications($userId) {
    $notifications = Notification::getNotificationsByUserId($userId);
    // Process and display notifications as needed
}

public function markAsRead($notificationId) {
    if (Notification::markAsRead($notificationId)) {
        echo "Notification marked as read.";
    } else {
        echo "Error marking notification as read.";
    }
}

public function delete($notificationId) {
    if (Notification::deleteNotification($notificationId)) {
        echo "Notification deleted.";
    } else {
        echo "Error deleting notification.";
    }
}
Database Structure
Make sure your notifications table in the database has the following structure:

CREATE TABLE notifications (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL,
    message TEXT NOT NULL,
    notification_type VARCHAR(50) NOT NULL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    is_read TINYINT(1) DEFAULT 0,
    FOREIGN KEY (user_id) REFERENCES users(id)
);
This Notification.php model provides a foundational structure for managing user notifications in your Online Learning Platform. 

8. models/Enrollment.php

<?php
class Enrollment {
    private $db;

    public function __construct($database) {
        $this->db = $database; // Assume $database is a PDO instance
    }

    // Enroll a user in a course
    public function enrollUserInCourse($userId, $courseId, $enrolledAt) {
        $query = "INSERT INTO enrollments (user_id, course_id, enrolled_at) 
                  VALUES (:user_id, :course_id, :enrolled_at)";

        $stmt = $this->db->prepare($query);
        $stmt->bindParam(':user_id', $userId);
        $stmt->bindParam(':course_id', $courseId);
        $stmt->bindParam(':enrolled_at', $enrolledAt);

        return $stmt->execute();
    }

    // Get all enrollments for a specific user
    public function getEnrollmentsByUserId($userId) {
        $query = "SELECT e.*, c.title FROM enrollments e 
                  JOIN courses c ON e.course_id = c.id 
                  WHERE e.user_id = :user_id ORDER BY e.enrolled_at DESC";
        $stmt = $this->db->prepare($query);
        $stmt->bindParam(':user_id', $userId);
        $stmt->execute();

        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    // Get all users enrolled in a specific course
    public function getUsersByCourseId($courseId) {
        $query = "SELECT e.*, u.name FROM enrollments e 
                  JOIN users u ON e.user_id = u.id 
                  WHERE e.course_id = :course_id";
        $stmt = $this->db->prepare($query);
        $stmt->bindParam(':course_id', $courseId);
        $stmt->execute();

        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    // Check if a user is enrolled in a specific course
    public function isUserEnrolled($userId, $courseId) {
        $query = "SELECT COUNT(*) FROM enrollments 
                  WHERE user_id = :user_id AND course_id = :course_id";
        $stmt = $this->db->prepare($query);
        $stmt->bindParam(':user_id', $userId);
        $stmt->bindParam(':course_id', $courseId);
        $stmt->execute();

        return $stmt->fetchColumn() > 0;
    }

    // Remove a user from a course
    public function removeUserFromCourse($userId, $courseId) {
        $query = "DELETE FROM enrollments WHERE user_id = :user_id AND course_id = :course_id";
        $stmt = $this->db->prepare($query);
        $stmt->bindParam(':user_id', $userId);
        $stmt->bindParam(':course_id', $courseId);

        return $stmt->execute();
    }
}
Explanation of Enrollment.php
  1. Constructor: Accepts a database connection (assumed to be a PDO instance) for database operations.
  2. Enroll User in Course Method: Inserts a new enrollment record into the enrollments table, linking a user to a specific course.
  3. Get Enrollments By User ID Method: Retrieves all enrollments for a specific user, including course titles, ordered by enrollment date.
  4. Get Users By Course ID Method: Fetches all users enrolled in a specific course, including user names.
  5. Is User Enrolled Method: Checks if a specific user is already enrolled in a specific course.
  6. Remove User From Course Method: Deletes the enrollment record linking a user to a course.
Integration
You can use this model within your controllers, such as EnrollmentController.php, to manage enrollment-related actions.

Example Usage in EnrollmentController.php

// In EnrollmentController.php

public function enroll($userId, $courseId) {
    $enrolledAt = date('Y-m-d H:i:s');

    if (Enrollment::enrollUserInCourse($userId, $courseId, $enrolledAt)) {
        echo "Successfully enrolled in the course.";
    } else {
        echo "Error enrolling in the course.";
    }
}

public function getUserEnrollments($userId) {
    $enrollments = Enrollment::getEnrollmentsByUserId($userId);
    // Process and display the enrollments as needed
}

public function getCourseUsers($courseId) {
    $users = Enrollment::getUsersByCourseId($courseId);
    // Process and display the users as needed
}

public function checkEnrollment($userId, $courseId) {
    if (Enrollment::isUserEnrolled($userId, $courseId)) {
        echo "User is already enrolled in this course.";
    } else {
        echo "User is not enrolled in this course.";
    }
}

public function unenroll($userId, $courseId) {
    if (Enrollment::removeUserFromCourse($userId, $courseId)) {
        echo "Successfully unenrolled from the course.";
    } else {
        echo "Error unenrolling from the course.";
    }
}
Database Structure
Ensure your enrollments table in the database has the following structure:

CREATE TABLE enrollments (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL,
    course_id INT NOT NULL,
    enrolled_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id),
    FOREIGN KEY (course_id) REFERENCES courses(id)
);
This Enrollment.php model provides a foundational structure for managing user enrollments in your Online Learning Platform. You can expand this model further based on your project’s requirements. If you have more files or models you need help with, feel free to ask!

4. Views

1.views/layouts/header.php
This file will typically contain the HTML structure for the header section, including links to CSS stylesheets, JavaScript files, and navigation elements that are consistent across different pages of the application.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo isset($title) ? $title : 'Online Learning Platform'; ?></title>
    <link rel="stylesheet" href="assets/css/styles.css">
    <script src="assets/js/scripts.js" defer></script>
</head>
<body>
    <header>
        <div class="container">
            <h1><a href="index.php">Online Learning Platform</a></h1>
            <nav>
                <ul>
                    <li><a href="index.php">Home</a></li>
                    <li><a href="courses.php">Courses</a></li>
                    <li><a href="assignments.php">Assignments</a></li>
                    <li><a href="quizzes.php">Quizzes</a></li>
                    <li><a href="notifications.php">Notifications</a></li>
                    <?php if (isset($_SESSION['user_id'])): ?>
                        <li><a href="profile.php">Profile</a></li>
                        <li><a href="logout.php">Logout</a></li>
                    <?php else: ?>
                        <li><a href="login.php">Login</a></li>
                        <li><a href="register.php">Register</a></li>
                    <?php endif; ?>
                </ul>
            </nav>
        </div>
    </header>
Explanation of header.php
  1. DOCTYPE and HTML Structure: Defines the document type and sets up the basic HTML structure, including language and character encoding.
  2. Head Section:
    1. Meta Tags: Provides character set and viewport settings for responsive design.
    2. Title: Sets the page title, which can be dynamic based on the $title variable passed from the controller.
    3. CSS Link: Includes the main stylesheet for the platform.
    4. JavaScript Link: Links to the main JavaScript file and defers its execution until the HTML is parsed.
    5. Header Section: Contains the main navigation and branding for the platform.
    6. Logo/Title: A clickable title that redirects to the home page.
  3. Navigation Menu:
    1. Links to various sections of the platform, including courses, assignments, quizzes, and notifications.
    2. Conditional rendering of user-related links based on whether a user is logged in or not.
  4. If the user is logged in, links to the profile and logout options are displayed.
  5. If the user is not logged in, links to the login and registration pages are displayed.
Integration
You can include this header file in your other view files using PHP's include or require statements. For example, in index.php, you would do the following:

<?php 
session_start(); // Start session for access to user information
include 'views/layouts/header.php'; 
?>
This way, the header will be consistently displayed across all pages, providing a cohesive user experience.

2.views/layouts/footer.php
 This file will contain the HTML structure for the footer section, including copyright information and any additional links or scripts that should be loaded at the end of the page.
   <footer>
        <div class="container">
            <p>&copy; <?php echo date("Y"); ?> Online Learning Platform. All rights reserved.</p>
            <ul>
                <li><a href="privacy.php">Privacy Policy</a></li>
                <li><a href="terms.php">Terms of Service</a></li>
                <li><a href="contact.php">Contact Us</a></li>
            </ul>
        </div>
    </footer>
</body>
</html>
Explanation of footer.php
  1. Footer Section: This contains important information and links relevant to the users of the platform.
  2. Copyright Notice: Dynamically generated using PHP's date() function to always display the current year, along with the name of the platform.
  3. Additional Links: Provides links to important pages such as Privacy Policy, Terms of Service, and Contact Us.
  4. Closing Tags: Closes the <body> and <html> tags, ensuring proper HTML structure.
Integration
You can include this footer file in your other view files using PHP's include or require statements, similar to how you would include the header. For example, in index.php, you would do the following:

<?php 
session_start(); // Start session for access to user information
include 'views/layouts/header.php'; 
?>

<!-- Page content goes here -->

<?php include 'views/layouts/footer.php'; ?>

Styling
You may want to include some CSS styles in your styles.css file to format the footer properly. Here’s an example of CSS styles you can add for the footer:

footer {
    background-color: #f8f9fa;
    padding: 20px;
    text-align: center;
}

footer p {
    margin: 0;
}

footer ul {
    list-style-type: none;
    padding: 0;
}

footer ul li {
    display: inline;
    margin: 0 10px;
}

footer a {
    text-decoration: none;
    color: #007bff;
}

footer a:hover {
    text-decoration: underline;
}
Summary
This footer.php file provides essential information and links, contributing to the overall user experience of your Online Learning Platform. 

3.views/layouts/sidebar.php
 The sidebar typically contains navigation links that are relevant to the user, such as links to manage courses, assignments, quizzes, and notifications, especially for admin users or instructors.

<aside>
    <div class="sidebar">
        <h2>Dashboard</h2>
        <ul>
            <li><a href="courses.php">Manage Courses</a></li>
            <li><a href="assignments.php">Manage Assignments</a></li>
            <li><a href="quizzes.php">Manage Quizzes</a></li>
            <li><a href="notifications.php">Notifications</a></li>
            <li><a href="users.php">Manage Users</a></li>
            <li><a href="profile.php">Profile</a></li>
        </ul>
    </div>
</aside>
Explanation of sidebar.php
  1. Sidebar Section: This section is designed to facilitate navigation for users, particularly those with administrative privileges.
  2. Dashboard Title: The title indicates that this sidebar is part of the dashboard area.
  3. Navigation Links: Contains links for:
    1. Managing courses
    2. Managing assignments
    3. Managing quizzes
    4. Viewing notifications
    5. Managing users (for admin users)
    6. Viewing the user's profile
Integration
You can include this sidebar file in your main layout files (e.g., dashboard.php, courses.php) using PHP's include or require statements. For example, in dashboard.php, you would do the following:

<?php 
session_start(); // Start session for access to user information
include 'views/layouts/header.php'; 
include 'views/layouts/sidebar.php'; 
?>

<!-- Main content area -->
<div class="main-content">
    <!-- Content specific to the current page goes here -->
</div>

<?php include 'views/layouts/footer.php'; ?>
Styling
You may want to include some CSS styles in your styles.css file to format the sidebar properly. Here’s an example of CSS styles you can add for the sidebar:

aside {
    width: 250px;
    background-color: #f4f4f4;
    padding: 20px;
    float: left;
}

.sidebar h2 {
    margin-top: 0;
}

.sidebar ul {
    list-style-type: none;
    padding: 0;
}

.sidebar ul li {
    margin: 10px 0;
}

.sidebar ul li a {
    text-decoration: none;
    color: #333;
}

.sidebar ul li a:hover {
    color: #007bff;
}
Summary
This sidebar.php file is a crucial component of your Online Learning Platform, enhancing the navigation experience for users, especially for those managing various aspects of the platform. 
4.views/auth/login.php
This file will contain the HTML form for users to log into their accounts, along with any necessary PHP code to handle the form submission.
<?php
session_start();
include '../../config.php'; // Include database connection
include '../layouts/header.php'; // Include header

// Check if user is already logged in, redirect to dashboard
if (isset($_SESSION['user_id'])) {
    header("Location: ../dashboard.php");
    exit();
}

// Initialize variables
$email = $password = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Get form data
    $email = trim($_POST['email']);
    $password = trim($_POST['password']);

    // Validate input
    if (empty($email) || empty($password)) {
        $error = "Email and password are required.";
    } else {
        // Check user credentials
        $stmt = $conn->prepare("SELECT id, name, password, role FROM users WHERE email = ?");
        $stmt->bind_param("s", $email);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows > 0) {
            $user = $result->fetch_assoc();
            // Verify password
            if (password_verify($password, $user['password'])) {
                // Store user information in session
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['user_name'] = $user['name'];
                $_SESSION['user_role'] = $user['role'];
                header("Location: ../dashboard.php"); // Redirect to dashboard
                exit();
            } else {
                $error = "Invalid email or password.";
            }
        } else {
            $error = "Invalid email or password.";
        }
    }
}
?>

<div class="container">
    <h2>Login</h2>
    <?php if ($error): ?>
        <div class="error"><?php echo $error; ?></div>
    <?php endif; ?>
    <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="POST">
        <div class="form-group">
            <label for="email">Email:</label>
            <input type="email" name="email" required>
        </div>
        <div class="form-group">
            <label for="password">Password:</label>
            <input type="password" name="password" required>
        </div>
        <button type="submit">Login</button>
    </form>
    <p>Don't have an account? <a href="register.php">Register here</a>.</p>
</div>

<?php include '../layouts/footer.php'; // Include footer ?>
Explanation of login.php
  1. Session Management: Starts a session to track user authentication.
  2. Header Inclusion: Includes the header layout at the top of the page.
  3. Redirect if Logged In: If the user is already logged in, they are redirected to the dashboard.
  4. Form Handling:Initializes variables to store email, password, and any error messages.
  5. Checks if the request method is POST (form submission).
  6. Retrieves and trims the input data for email and password.
  7. Validates the input to ensure both fields are filled.
  8. Prepares and executes a SQL statement to fetch the user by email.
  9. If a user is found, it verifies the password using password_verify().
  10. If the credentials are valid, it stores the user ID, name, and role in session variables and redirects to the dashboard.
  11. If not, it sets an error message indicating invalid credentials.
  12. HTML Structure:Displays the login form.
Shows any error messages if authentication fails.
Provides a link to the registration page for new users.
Styling
You may want to include some CSS styles in your styles.css file to format the login page properly. Here’s an example of CSS styles you can add for the login form:

.container {
    width: 400px;
    margin: 50px auto;
    padding: 20px;
    border: 1px solid #ccc;
    border-radius: 5px;
    background-color: #f9f9f9;
}

h2 {
    text-align: center;
}

.form-group {
    margin-bottom: 15px;
}

.label {
    display: block;
    margin-bottom: 5px;
}

input[type="email"],
input[type="password"] {
    width: 100%;
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
}

button {
    width: 100%;
    padding: 10px;
    background-color: #007bff;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
}

button:hover {
    background-color: #0056b3;
}

.error {
    color: red;
    margin-bottom: 15px;
}
Summary
This login.php file provides the functionality for users to log into their accounts, handling authentication and session management.

5.views/auth/register.php

This file will contain the HTML form for new users to create their accounts, along with PHP code to handle the form submission and user registration.
<?php
session_start();
include '../../config.php'; // Include database connection
include '../layouts/header.php'; // Include header

// Initialize variables
$name = $email = $password = $confirm_password = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Get form data
    $name = trim($_POST['name']);
    $email = trim($_POST['email']);
    $password = trim($_POST['password']);
    $confirm_password = trim($_POST['confirm_password']);

    // Validate input
    if (empty($name) || empty($email) || empty($password) || empty($confirm_password)) {
        $error = "All fields are required.";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = "Invalid email format.";
    } elseif ($password !== $confirm_password) {
        $error = "Passwords do not match.";
    } else {
        // Check if email already exists
        $stmt = $conn->prepare("SELECT id FROM users WHERE email = ?");
        $stmt->bind_param("s", $email);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows > 0) {
            $error = "Email is already in use.";
        } else {
            // Hash the password
            $hashed_password = password_hash($password, PASSWORD_DEFAULT);

            // Insert new user into database
            $stmt = $conn->prepare("INSERT INTO users (name, email, password, role, created_at) VALUES (?, ?, ?, 'student', NOW())");
            $stmt->bind_param("sss", $name, $email, $hashed_password);

            if ($stmt->execute()) {
                // Redirect to login page
                header("Location: login.php");
                exit();
            } else {
                $error = "Registration failed. Please try again.";
            }
        }
    }
}
?>

<div class="container">
    <h2>Register</h2>
    <?php if ($error): ?>
        <div class="error"><?php echo $error; ?></div>
    <?php endif; ?>
    <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="POST">
        <div class="form-group">
            <label for="name">Name:</label>
            <input type="text" name="name" required>
        </div>
        <div class="form-group">
            <label for="email">Email:</label>
            <input type="email" name="email" required>
        </div>
        <div class="form-group">
            <label for="password">Password:</label>
            <input type="password" name="password" required>
        </div>
        <div class="form-group">
            <label for="confirm_password">Confirm Password:</label>
            <input type="password" name="confirm_password" required>
        </div>
        <button type="submit">Register</button>
    </form>
    <p>Already have an account? <a href="login.php">Login here</a>.</p>
</div>

<?php include '../layouts/footer.php'; // Include footer ?>

Explanation of register.php
  1. Session Management: Starts a session to handle user registrations.
  2. Header Inclusion: Includes the header layout at the top of the page.
  3. Form Handling:Initializes variables to store name, email, password, confirm password, and any error messages.
  4. Checks if the request method is POST (form submission).
  5. Retrieves and trims the input data for name, email, password, and confirm password.
  6. Validates the input:Ensures all fields are filled.
  7. Validates the email format.Checks if the passwords match.
  8. Checks if the email already exists in the database. If it does, it sets an error message.
  9. If the email is unique, it hashes the password using password_hash().
  10. Inserts the new user into the users table with a default role of 'student' and the current timestamp.
  11. On successful registration, it redirects the user to the login page.
  12. HTML Structure:Displays the registration form.
Shows any error messages if registration fails.
Provides a link to the login page for users who already have an account.
Styling
You may want to include some CSS styles in your styles.css file to format the registration page properly. Here’s an example of CSS styles you can add for the registration form:

.container {
    width: 400px;
    margin: 50px auto;
    padding: 20px;
    border: 1px solid #ccc;
    border-radius: 5px;
    background-color: #f9f9f9;
}

h2 {
    text-align: center;
}

.form-group {
    margin-bottom: 15px;
}

.label {
    display: block;
    margin-bottom: 5px;
}

input[type="text"],
input[type="email"],
input[type="password"] {
    width: 100%;
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
}

button {
    width: 100%;
    padding: 10px;
    background-color: #007bff;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
}

button:hover {
    background-color: #0056b3;
}

.error {
    color: red;
    margin-bottom: 15px;
}
Summary
This register.php file provides the functionality for new users to create their accounts, handling registration logic and validations. 

6.views/dashboard/dashboard.php

This file will serve as the main dashboard for users (students or admins), displaying an overview of their enrolled courses, assignments, quizzes, and notifications.

<?php
session_start();
include '../../config.php'; // Include database connection
include '../layouts/header.php'; // Include header
include '../layouts/sidebar.php'; // Include sidebar

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header("Location: ../auth/login.php");
    exit();
}

// Fetch user information
$user_id = $_SESSION['user_id'];
$stmt = $conn->prepare("SELECT name, email FROM users WHERE id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$user_result = $stmt->get_result();
$user = $user_result->fetch_assoc();

// Fetch enrolled courses
$stmt = $conn->prepare("SELECT c.id, c.title FROM courses c
JOIN enrollments e ON c.id = e.course_id
WHERE e.user_id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$courses_result = $stmt->get_result();

// Fetch assignments
$stmt = $conn->prepare("SELECT a.id, a.title, a.due_date FROM assignments a
JOIN courses c ON a.course_id = c.id
JOIN enrollments e ON c.id = e.course_id
WHERE e.user_id = ?
ORDER BY a.due_date ASC");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$assignments_result = $stmt->get_result();

// Fetch quizzes
$stmt = $conn->prepare("SELECT q.id, q.title FROM quizzes q
JOIN courses c ON q.course_id = c.id
JOIN enrollments e ON c.id = e.course_id
WHERE e.user_id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$quizzes_result = $stmt->get_result();

// Fetch notifications
$stmt = $conn->prepare("SELECT n.message, n.created_at FROM notifications n
WHERE n.user_id = ? ORDER BY n.created_at DESC");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$notifications_result = $stmt->get_result();
?>

<div class="container">
    <h2>Welcome, <?php echo htmlspecialchars($user['name']); ?>!</h2>

    <div class="dashboard-section">
        <h3>Your Courses</h3>
        <ul>
            <?php while ($course = $courses_result->fetch_assoc()): ?>
                <li>
                    <a href="../courses/view.php?id=<?php echo $course['id']; ?>">
                        <?php echo htmlspecialchars($course['title']); ?>
                    </a>
                </li>
            <?php endwhile; ?>
        </ul>
    </div>

    <div class="dashboard-section">
        <h3>Your Assignments</h3>
        <ul>
            <?php while ($assignment = $assignments_result->fetch_assoc()): ?>
                <li>
                    <a href="../assignments/view.php?id=<?php echo $assignment['id']; ?>">
                        <?php echo htmlspecialchars($assignment['title']); ?> (Due: <?php echo $assignment['due_date']; ?>)
                    </a>
                </li>
            <?php endwhile; ?>
        </ul>
    </div>

    <div class="dashboard-section">
        <h3>Your Quizzes</h3>
        <ul>
            <?php while ($quiz = $quizzes_result->fetch_assoc()): ?>
                <li>
                    <a href="../quizzes/view.php?id=<?php echo $quiz['id']; ?>">
                        <?php echo htmlspecialchars($quiz['title']); ?>
                    </a>
                </li>
            <?php endwhile; ?>
        </ul>
    </div>

    <div class="dashboard-section">
        <h3>Notifications</h3>
        <ul>
            <?php while ($notification = $notifications_result->fetch_assoc()): ?>
                <li>
                    <?php echo htmlspecialchars($notification['message']); ?> (<?php echo $notification['created_at']; ?>)
                </li>
            <?php endwhile; ?>
        </ul>
    </div>
</div>

<?php include '../layouts/footer.php'; // Include footer ?>

Explanation of dashboard.php
  1. Session Management: Starts a session and checks if the user is logged in. If not, it redirects them to the login page.
  2. Header and Sidebar Inclusion: Includes the header and sidebar layouts.
  3. Fetch User Information: Retrieves the logged-in user’s name and email from the users table based on their user ID.
  4. Fetch Enrolled Courses: Retrieves the courses the user is enrolled in by joining the courses and enrollments tables.
  5. Fetch Assignments: Retrieves assignments associated with the user’s enrolled courses, ordered by due date.
  6. Fetch Quizzes: Retrieves quizzes associated with the user’s enrolled courses.
  7. Fetch Notifications: Retrieves notifications for the user, ordered by the created date.
  8. HTML Structure:Displays a welcome message to the user.
  9. Lists the user's enrolled courses, assignments (with due dates), quizzes, and notifications.
  10. Each item is clickable, linking to their respective view pages.
Styling
You may want to include additional CSS styles in your styles.css file for formatting the dashboard. Here’s an example of CSS styles you can add for the dashboard:


.container {
    width: 80%;
    margin: 20px auto;
    padding: 20px;
    background-color: #f9f9f9;
    border-radius: 5px;
}

.dashboard-section {
    margin-bottom: 30px;
}

h2 {
    text-align: center;
}

h3 {
    border-bottom: 1px solid #ccc;
    padding-bottom: 10px;
}

ul {
    list-style-type: none;
    padding: 0;
}

ul li {
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 5px;
    margin-bottom: 5px;
}

ul li a {
    text-decoration: none;
    color: #007bff;
}

ul li a:hover {
    text-decoration: underline;
}
Summary
This dashboard.php file serves as the central hub for users on the Online Learning Platform, providing a quick overview of their courses, assignments, quizzes, and notifications.

7.views/courses/course_list.php
 
This file will display a list of courses available on the platform, allowing users to view more details or enroll in a course.
<?php
session_start();
include '../../config.php'; // Include database connection
include '../layouts/header.php'; // Include header
include '../layouts/sidebar.php'; // Include sidebar

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header("Location: ../auth/login.php");
    exit();
}

// Fetch all courses
$stmt = $conn->prepare("SELECT id, title, description FROM courses");
$stmt->execute();
$courses_result = $stmt->get_result();
?>

<div class="container">
    <h2>Available Courses</h2>

    <table class="table">
        <thead>
            <tr>
                <th>Course Title</th>
                <th>Description</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            <?php while ($course = $courses_result->fetch_assoc()): ?>
                <tr>
                    <td><?php echo htmlspecialchars($course['title']); ?></td>
                    <td><?php echo htmlspecialchars($course['description']); ?></td>
                    <td>
                        <a href="view.php?id=<?php echo $course['id']; ?>" class="btn btn-info">View</a>
                        <a href="../../controllers/EnrollmentController.php?action=enroll&course_id=<?php echo $course['id']; ?>" class="btn btn-success">Enroll</a>
                    </td>
                </tr>
            <?php endwhile; ?>
        </tbody>
    </table>
</div>

<?php include '../layouts/footer.php'; // Include footer ?>

Explanation of course_list.php
  1. Session Management: Starts a session and checks if the user is logged in. If not, it redirects them to the login page.
  2. Header and Sidebar Inclusion: Includes the header and sidebar layouts.
  3. Fetch Courses: Prepares and executes a SQL statement to fetch all courses from the courses table, retrieving the course ID, title, and description.
  4. HTML Structure:Displays a title for the courses section.
  5. Utilizes a table to list the courses.
  6. For each course, it shows the title, description, and action buttons:
  7. View: Links to a course detail page (assuming it will be implemented in view.php).
  8. Enroll: Sends a request to the EnrollmentController to enroll the user in the selected course.
Styling
You can use Bootstrap classes for table styling and buttons, or you can add custom styles in your styles.css file. If you are using Bootstrap, ensure you have included the Bootstrap CSS in your header file. Here's a basic style for your table:

.table {
    width: 100%;
    margin: 20px 0;
    border-collapse: collapse;
}

.table th,
.table td {
    padding: 10px;
    text-align: left;
    border-bottom: 1px solid #ddd;
}

.table th {
    background-color: #f2f2f2;
}
Summary
The course_list.php file provides users with a straightforward interface to view available courses and enroll in them.

8.views/courses/course_create.php
This file will allow admins to create new courses by filling out a form with the course title, description, and other relevant details.
<?php
session_start();
include '../../config.php'; // Include database connection
include '../layouts/header.php'; // Include header
include '../layouts/sidebar.php'; // Include sidebar

// Check if user is logged in and is an admin
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    header("Location: ../auth/login.php");
    exit();
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $title = trim($_POST['title']);
    $description = trim($_POST['description']);

    // Insert new course into the database
    $stmt = $conn->prepare("INSERT INTO courses (title, description) VALUES (?, ?)");
    $stmt->bind_param("ss", $title, $description);

    if ($stmt->execute()) {
        echo "<script>alert('Course created successfully!'); window.location.href='course_list.php';</script>";
    } else {
        echo "<script>alert('Error creating course: " . $stmt->error . "');</script>";
    }
}
?>

<div class="container">
    <h2>Create New Course</h2>
    <form method="POST" action="">
        <div class="form-group">
            <label for="title">Course Title</label>
            <input type="text" class="form-control" id="title" name="title" required>
        </div>
        <div class="form-group">
            <label for="description">Course Description</label>
            <textarea class="form-control" id="description" name="description" rows="5" required></textarea>
        </div>
        <button type="submit" class="btn btn-primary">Create Course</button>
        <a href="course_list.php" class="btn btn-secondary">Cancel</a>
    </form>
</div>

<?php include '../layouts/footer.php'; // Include footer ?>

Explanation of course_create.php
  1. Session Management: Starts a session and checks if the user is logged in and has admin privileges. If not, it redirects them to the login page.
  2. Form Handling:If the form is submitted via a POST request, it retrieves the course title and description from the form inputs.
  3. Prepares and executes a SQL statement to insert the new course into the courses table.
  4. Displays an alert message to inform the user whether the course was created successfully or if there was an error.
  5. HTML Form:Contains a form for creating a new course, including fields for the course title and description.
  6. Includes a submit button to create the course and a cancel button that redirects back to the course list.
Styling
You can use Bootstrap classes for styling the form elements and buttons. Ensure you have included Bootstrap CSS in your header file. If you want to add some custom styles, here's a basic example for the form:

.container {
    max-width: 600px;
    margin: 20px auto;
}

.form-group {
    margin-bottom: 15px;
}

h2 {
    margin-bottom: 20px;
}
Summary
The course_create.php file provides an interface for admins to create new courses by filling out a simple form. Once the course is created, it redirects the user to the course list page. 

9.views/courses/course_edit.php

This file allows admins to edit existing courses by updating the course title and description.
<?php
session_start();
include '../../config.php'; // Include database connection
include '../layouts/header.php'; // Include header
include '../layouts/sidebar.php'; // Include sidebar

// Check if user is logged in and is an admin
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    header("Location: ../auth/login.php");
    exit();
}

// Get the course ID from the URL
if (isset($_GET['id'])) {
    $course_id = intval($_GET['id']);

    // Fetch the course details
    $stmt = $conn->prepare("SELECT title, description FROM courses WHERE id = ?");
    $stmt->bind_param("i", $course_id);
    $stmt->execute();
    $course_result = $stmt->get_result();

    if ($course_result->num_rows == 0) {
        echo "<script>alert('Course not found!'); window.location.href='course_list.php';</script>";
        exit();
    }

    $course = $course_result->fetch_assoc();
} else {
    echo "<script>alert('Invalid course ID!'); window.location.href='course_list.php';</script>";
    exit();
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $title = trim($_POST['title']);
    $description = trim($_POST['description']);

    // Update course in the database
    $stmt = $conn->prepare("UPDATE courses SET title = ?, description = ? WHERE id = ?");
    $stmt->bind_param("ssi", $title, $description, $course_id);

    if ($stmt->execute()) {
        echo "<script>alert('Course updated successfully!'); window.location.href='course_list.php';</script>";
    } else {
        echo "<script>alert('Error updating course: " . $stmt->error . "');</script>";
    }
}
?>

<div class="container">
    <h2>Edit Course</h2>
    <form method="POST" action="">
        <div class="form-group">
            <label for="title">Course Title</label>
            <input type="text" class="form-control" id="title" name="title" value="<?php echo htmlspecialchars($course['title']); ?>" required>
        </div>
        <div class="form-group">
            <label for="description">Course Description</label>
            <textarea class="form-control" id="description" name="description" rows="5" required><?php echo htmlspecialchars($course['description']); ?></textarea>
        </div>
        <button type="submit" class="btn btn-primary">Update Course</button>
        <a href="course_list.php" class="btn btn-secondary">Cancel</a>
    </form>
</div>

<?php include '../layouts/footer.php'; // Include footer ?>

Explanation of course_edit.php
  1. Session Management: Starts a session and checks if the user is logged in and has admin privileges. If not, it redirects them to the login page.
  2. Fetch Course Details:Retrieves the course ID from the URL.
  3. Prepares and executes a SQL statement to fetch the course's current title and description from the courses table.
  4. If the course is not found, it alerts the user and redirects them to the course list.
  5. Form Handling:If the form is submitted via a POST request, it retrieves the updated course title and description.
  6. Prepares and executes a SQL statement to update the course details in the courses table.
  7. Displays an alert message to inform the user whether the course was updated successfully or if there was an error.
  8. HTML Form:Contains a form for editing the course, pre-filling the title and description fields with the current values.
  9. Includes a submit button to update the course and a cancel button that redirects back to the course list.
Styling
As with the previous files, you can use Bootstrap classes for styling the form elements and buttons. Ensure Bootstrap CSS is included in your header file. Here’s a basic style for the edit form:

.container {
    max-width: 600px;
    margin: 20px auto;
}

.form-group {
    margin-bottom: 15px;
}

h2 {
    margin-bottom: 20px;
}
Summary
The course_edit.php file provides a user-friendly interface for admins to edit existing courses. It fetches the current course details, allows the admin to update them, and provides feedback on the success of the operation.


10.views/courses/course_view.php
This file displays the details of a specific course, including its title, description, modules, assignments, and quizzes.

<?php
session_start();
include '../../config.php'; // Include database connection
include '../layouts/header.php'; // Include header
include '../layouts/sidebar.php'; // Include sidebar

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header("Location: ../auth/login.php");
    exit();
}

// Get the course ID from the URL
if (isset($_GET['id'])) {
    $course_id = intval($_GET['id']);

    // Fetch course details
    $stmt = $conn->prepare("SELECT title, description FROM courses WHERE id = ?");
    $stmt->bind_param("i", $course_id);
    $stmt->execute();
    $course_result = $stmt->get_result();

    if ($course_result->num_rows == 0) {
        echo "<script>alert('Course not found!'); window.location.href='course_list.php';</script>";
        exit();
    }

    $course = $course_result->fetch_assoc();
} else {
    echo "<script>alert('Invalid course ID!'); window.location.href='course_list.php';</script>";
    exit();
}

// Fetch modules, assignments, and quizzes for this course
$modules_stmt = $conn->prepare("SELECT id, title FROM modules WHERE course_id = ?");
$modules_stmt->bind_param("i", $course_id);
$modules_stmt->execute();
$modules_result = $modules_stmt->get_result();

$assignments_stmt = $conn->prepare("SELECT id, title FROM assignments WHERE course_id = ?");
$assignments_stmt->bind_param("i", $course_id);
$assignments_stmt->execute();
$assignments_result = $assignments_stmt->get_result();

$quizzes_stmt = $conn->prepare("SELECT id, title FROM quizzes WHERE course_id = ?");
$quizzes_stmt->bind_param("i", $course_id);
$quizzes_stmt->execute();
$quizzes_result = $quizzes_stmt->get_result();
?>

<div class="container">
    <h2><?php echo htmlspecialchars($course['title']); ?></h2>
    <p><strong>Description:</strong></p>
    <p><?php echo nl2br(htmlspecialchars($course['description'])); ?></p>

    <h3>Modules</h3>
    <ul>
        <?php while ($module = $modules_result->fetch_assoc()) { ?>
            <li>
                <a href="module_view.php?id=<?php echo $module['id']; ?>"><?php echo htmlspecialchars($module['title']); ?></a>
            </li>
        <?php } ?>
    </ul>

    <h3>Assignments</h3>
    <ul>
        <?php while ($assignment = $assignments_result->fetch_assoc()) { ?>
            <li>
                <a href="assignment_view.php?id=<?php echo $assignment['id']; ?>"><?php echo htmlspecialchars($assignment['title']); ?></a>
            </li>
        <?php } ?>
    </ul>

    <h3>Quizzes</h3>
    <ul>
        <?php while ($quiz = $quizzes_result->fetch_assoc()) { ?>
            <li>
                <a href="quiz_view.php?id=<?php echo $quiz['id']; ?>"><?php echo htmlspecialchars($quiz['title']); ?></a>
            </li>
        <?php } ?>
    </ul>

    <a href="course_list.php" class="btn btn-secondary">Back to Course List</a>
</div>

<?php include '../layouts/footer.php'; // Include footer ?>
Explanation of course_view.php
  1. Session Management: Starts a session and checks if the user is logged in. If not, it redirects them to the login page.
  2. Fetch Course Details:Retrieves the course ID from the URL.
  3. Prepares and executes a SQL statement to fetch the course's title and description from the courses table.
  4. If the course is not found, it alerts the user and redirects them to the course list.
  5. Fetch Related Data:Retrieves modules, assignments, and quizzes associated with the course by executing separate SQL statements for each.
  6. Each statement binds the course_id to filter the results accordingly.
  7. Display Course Details:Displays the course title and description.
  8. Lists the modules, assignments, and quizzes as clickable links that lead to their respective view pages (you'll need to create module_view.php, assignment_view.php, and quiz_view.php for this).
  9. HTML Structure:Utilizes Bootstrap classes for styling and layout.Provides a back button to return to the course list.
Styling
You can use Bootstrap classes for styling the layout. Ensure Bootstrap CSS is included in your header file. Here’s a basic style for the course view:

.container {
    max-width: 800px;
    margin: 20px auto;
}

h2 {
    margin-bottom: 15px;
}

h3 {
    margin-top: 20px;
}

ul {
    list-style-type: none;
    padding: 0;
}
Summary
The course_view.php file provides a comprehensive view of a specific course, detailing its modules, assignments, and quizzes. This enhances the user experience by allowing users to navigate to related content easily. 

11.views/modules/module_list.php

This file displays a list of modules for a specific course, allowing users to view, create, and manage modules.<?php
session_start();
include '../../config.php'; // Include database connection
include '../layouts/header.php'; // Include header
include '../layouts/sidebar.php'; // Include sidebar

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header("Location: ../auth/login.php");
    exit();
}

// Get the course ID from the URL
if (isset($_GET['course_id'])) {
    $course_id = intval($_GET['course_id']);

    // Fetch course details to display
    $course_stmt = $conn->prepare("SELECT title FROM courses WHERE id = ?");
    $course_stmt->bind_param("i", $course_id);
    $course_stmt->execute();
    $course_result = $course_stmt->get_result();

    if ($course_result->num_rows == 0) {
        echo "<script>alert('Course not found!'); window.location.href='../courses/course_list.php';</script>";
        exit();
    }

    $course = $course_result->fetch_assoc();
} else {
    echo "<script>alert('Invalid course ID!'); window.location.href='../courses/course_list.php';</script>";
    exit();
}

// Fetch modules for the course
$modules_stmt = $conn->prepare("SELECT id, title FROM modules WHERE course_id = ?");
$modules_stmt->bind_param("i", $course_id);
$modules_stmt->execute();
$modules_result = $modules_stmt->get_result();
?>

<div class="container">
    <h2>Modules for Course: <?php echo htmlspecialchars($course['title']); ?></h2>
    
    <a href="module_create.php?course_id=<?php echo $course_id; ?>" class="btn btn-primary">Add New Module</a>

    <h3>Module List</h3>
    <table class="table">
        <thead>
            <tr>
                <th>ID</th>
                <th>Title</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php while ($module = $modules_result->fetch_assoc()) { ?>
                <tr>
                    <td><?php echo htmlspecialchars($module['id']); ?></td>
                    <td><?php echo htmlspecialchars($module['title']); ?></td>
                    <td>
                        <a href="module_view.php?id=<?php echo $module['id']; ?>" class="btn btn-info">View</a>
                        <a href="module_edit.php?id=<?php echo $module['id']; ?>" class="btn btn-warning">Edit</a>
                        <a href="module_delete.php?id=<?php echo $module['id']; ?>" class="btn btn-danger" onclick="return confirm('Are you sure you want to delete this module?');">Delete</a>
                    </td>
                </tr>
            <?php } ?>
        </tbody>
    </table>

    <a href="../courses/course_view.php?id=<?php echo $course_id; ?>" class="btn btn-secondary">Back to Course</a>
</div>

<?php include '../layouts/footer.php'; // Include footer ?>

Explanation of module_list.php
  1. Session Management: Starts a session and checks if the user is logged in. If not, it redirects them to the login page.
  2. Fetch Course ID: Retrieves the course ID from the URL to display the modules for that specific course.
  3. Fetch Course Details:Prepares and executes a SQL statement to get the course title based on the course_id.
  4. If the course is not found, it alerts the user and redirects them to the course list.
  5. Fetch Modules:Prepares and executes a SQL statement to fetch all modules related to the specified course.
  6. Display Modules:Displays a list of modules in a table format.
  7. Each module has options to view, edit, or delete.
  8. Add New Module: Provides a button to navigate to the module creation page (module_create.php).
  9. HTML Structure:Utilizes Bootstrap classes for styling the layout.Contains a button to navigate back to the course view.
Summary
The module_list.php file allows users to manage modules related to a specific course, providing options to view, edit, delete, and add new modules. This enhances user interactivity within the course management functionality. 


12.views/modules/module_create.php

This file allows users to create a new module associated with a specific course.

<?php
session_start();
include '../../config.php'; // Include database connection
include '../layouts/header.php'; // Include header
include '../layouts/sidebar.php'; // Include sidebar

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header("Location: ../auth/login.php");
    exit();
}

// Check if course ID is provided
if (!isset($_GET['course_id'])) {
    echo "<script>alert('Invalid course ID!'); window.location.href='module_list.php';</script>";
    exit();
}

$course_id = intval($_GET['course_id']);

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $title = trim($_POST['title']);
    $description = trim($_POST['description']);

    // Validate input
    if (empty($title) || empty($description)) {
        $error = "All fields are required.";
    } else {
        // Insert new module into the database
        $stmt = $conn->prepare("INSERT INTO modules (course_id, title, description) VALUES (?, ?, ?)");
        $stmt->bind_param("iss", $course_id, $title, $description);

        if ($stmt->execute()) {
            header("Location: module_list.php?course_id=" . $course_id);
            exit();
        } else {
            $error = "Error creating module. Please try again.";
        }
    }
}
?>

<div class="container">
    <h2>Create New Module</h2>

    <?php if (isset($error)): ?>
        <div class="alert alert-danger"><?php echo htmlspecialchars($error); ?></div>
    <?php endif; ?>

    <form action="" method="POST">
        <div class="form-group">
            <label for="title">Module Title</label>
            <input type="text" class="form-control" id="title" name="title" required>
        </div>
        <div class="form-group">
            <label for="description">Description</label>
            <textarea class="form-control" id="description" name="description" rows="4" required></textarea>
        </div>
        <button type="submit" class="btn btn-primary">Create Module</button>
        <a href="module_list.php?course_id=<?php echo $course_id; ?>" class="btn btn-secondary">Cancel</a>
    </form>
</div>

<?php include '../layouts/footer.php'; // Include footer ?>
Explanation of module_create.php
  1. Session Management: Starts a session and checks if the user is logged in. If not, it redirects them to the login page.
  2. Check Course ID: Validates if the course_id is provided in the URL. If not, it alerts the user and redirects them back to the module list.
  3. Form Submission Handling:Checks if the request method is POST, indicating that the form has been submitted.
  4. Retrieves and trims the title and description from the form input.
  5. Validates that both fields are not empty.
  6. If valid, it prepares and executes an SQL statement to insert the new module into the modules table.
  7. If the insertion is successful, it redirects to the module_list.php page for the course.
  8. If there's an error, it sets an error message to be displayed to the user.
  9. HTML Form Structure:Utilizes Bootstrap for styling the layout.
Contains input fields for module title and description.
Includes a submit button to create the module and a cancel button to go back to the module list.
Summary
The module_create.php file provides a form for users to create a new module for a specific course, handling validation and database insertion seamlessly. 

13. views/modules/module_edit.php

This file allows users to edit an existing module associated with a specific course.

<?php
session_start();
include '../../config.php'; // Include database connection
include '../layouts/header.php'; // Include header
include '../layouts/sidebar.php'; // Include sidebar

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header("Location: ../auth/login.php");
    exit();
}

// Check if module ID is provided
if (!isset($_GET['id'])) {
    echo "<script>alert('Invalid module ID!'); window.location.href='module_list.php';</script>";
    exit();
}

$module_id = intval($_GET['id']);

// Fetch the module details from the database
$stmt = $conn->prepare("SELECT title, description, course_id FROM modules WHERE id = ?");
$stmt->bind_param("i", $module_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows == 0) {
    echo "<script>alert('Module not found!'); window.location.href='module_list.php';</script>";
    exit();
}

$module = $result->fetch_assoc();
$course_id = $module['course_id'];

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $title = trim($_POST['title']);
    $description = trim($_POST['description']);

    // Validate input
    if (empty($title) || empty($description)) {
        $error = "All fields are required.";
    } else {
        // Update the module in the database
        $update_stmt = $conn->prepare("UPDATE modules SET title = ?, description = ? WHERE id = ?");
        $update_stmt->bind_param("ssi", $title, $description, $module_id);

        if ($update_stmt->execute()) {
            header("Location: module_list.php?course_id=" . $course_id);
            exit();
        } else {
            $error = "Error updating module. Please try again.";
        }
    }
}
?>

<div class="container">
    <h2>Edit Module</h2>

    <?php if (isset($error)): ?>
        <div class="alert alert-danger"><?php echo htmlspecialchars($error); ?></div>
    <?php endif; ?>

    <form action="" method="POST">
        <div class="form-group">
            <label for="title">Module Title</label>
            <input type="text" class="form-control" id="title" name="title" value="<?php echo htmlspecialchars($module['title']); ?>" required>
        </div>
        <div class="form-group">
            <label for="description">Description</label>
            <textarea class="form-control" id="description" name="description" rows="4" required><?php echo htmlspecialchars($module['description']); ?></textarea>
        </div>
        <button type="submit" class="btn btn-primary">Update Module</button>
        <a href="module_list.php?course_id=<?php echo $course_id; ?>" class="btn btn-secondary">Cancel</a>
    </form>
</div>

<?php include '../layouts/footer.php'; // Include footer ?>
Explanation of module_edit.php
  1. Session Management: Starts a session and checks if the user is logged in. If not, it redirects them to the login page.
  2. Check Module ID: Validates if the id is provided in the URL. If not, it alerts the user and redirects them back to the module list.
  3. Fetch Module Details:Prepares and executes a SQL statement to fetch the module's title, description, and associated course ID based on the provided module ID.
  4. If no module is found, it alerts the user and redirects them back to the module list.
  5. Form Submission Handling:Checks if the request method is POST, indicating that the form has been submitted.
  6. Retrieves and trims the title and description from the form input.
  7. Validates that both fields are not empty.
  8. If valid, it prepares and executes an SQL statement to update the existing module in the modules table.
  9. If the update is successful, it redirects to the module_list.php page for the associated course.
  10. If there's an error, it sets an error message to be displayed to the user.
  11. HTML Form Structure:Utilizes Bootstrap for styling the layout.
  12. Contains input fields pre-filled with the existing module title and description.
  13. Includes a submit button to update the module and a cancel button to go back to the module list.
Summary
The module_edit.php file allows users to edit the details of a specific module, providing a form for input and handling validation and database updates seamlessly. 

15.views/assignments/assignment_list.php

This file displays a list of assignments associated with a specific course, allowing users to view, edit, and delete assignments.

<?php
session_start();
include '../../config.php'; // Include database connection
include '../layouts/header.php'; // Include header
include '../layouts/sidebar.php'; // Include sidebar

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header("Location: ../auth/login.php");
    exit();
}

// Check if course ID is provided
if (!isset($_GET['course_id'])) {
    echo "<script>alert('Invalid course ID!'); window.location.href='course_list.php';</script>";
    exit();
}

$course_id = intval($_GET['course_id']);

// Fetch assignments for the specific course
$stmt = $conn->prepare("SELECT * FROM assignments WHERE course_id = ?");
$stmt->bind_param("i", $course_id);
$stmt->execute();
$result = $stmt->get_result();
?>

<div class="container">
    <h2>Assignments for Course ID: <?php echo htmlspecialchars($course_id); ?></h2>
    <a href="assignment_create.php?course_id=<?php echo $course_id; ?>" class="btn btn-primary mb-3">Create New Assignment</a>

    <table class="table table-bordered">
        <thead>
            <tr>
                <th>ID</th>
                <th>Title</th>
                <th>Description</th>
                <th>Due Date</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php if ($result->num_rows > 0): ?>
                <?php while ($assignment = $result->fetch_assoc()): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($assignment['id']); ?></td>
                        <td><?php echo htmlspecialchars($assignment['title']); ?></td>
                        <td><?php echo htmlspecialchars($assignment['description']); ?></td>
                        <td><?php echo htmlspecialchars($assignment['due_date']); ?></td>
                        <td>
                            <a href="assignment_edit.php?id=<?php echo $assignment['id']; ?>&course_id=<?php echo $course_id; ?>" class="btn btn-warning btn-sm">Edit</a>
                            <a href="assignment_delete.php?id=<?php echo $assignment['id']; ?>&course_id=<?php echo $course_id; ?>" class="btn btn-danger btn-sm" onclick="return confirm('Are you sure you want to delete this assignment?');">Delete</a>
                        </td>
                    </tr>
                <?php endwhile; ?>
            <?php else: ?>
                <tr>
                    <td colspan="5" class="text-center">No assignments found for this course.</td>
                </tr>
            <?php endif; ?>
        </tbody>
    </table>
</div>

<?php include '../layouts/footer.php'; // Include footer ?>

Explanation of assignment_list.php
  1. Session Management: Starts a session and checks if the user is logged in. If not, it redirects them to the login page.
  2. Check Course ID: Validates if the course_id is provided in the URL. If not, it alerts the user and redirects them back to the course list.
  3. Fetch Assignments:Prepares and executes a SQL statement to fetch all assignments associated with the provided course ID.
  4. The result is stored in $result.
  5. HTML Structure:Displays a header showing the course ID for which the assignments are being listed.
  6. Includes a button to create a new assignment, which links to the assignment_create.php file with the course ID as a query parameter.
  7. Uses a Bootstrap-styled table to display the list of assignments, including their ID, title, description, due date, and actions (Edit and Delete).
  8. If there are no assignments, it shows a message indicating that no assignments are found.
  9. Action Buttons:Each assignment row contains two action buttons:
  10. Edit: Links to the assignment_edit.php page with the assignment ID and course ID.
  11. Delete: Links to a assignment_delete.php page to delete the assignment, with a confirmation prompt before proceeding.
Summary
The assignment_list.php file provides a comprehensive view of assignments associated with a specific course, allowing users to create, edit, and delete assignments as needed. 

15.views/assignments/assignment_create.php

This file allows users to create a new assignment associated with a specific course.

<?php
session_start();
include '../../config.php'; // Include database connection
include '../layouts/header.php'; // Include header
include '../layouts/sidebar.php'; // Include sidebar

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header("Location: ../auth/login.php");
    exit();
}

// Check if course ID is provided
if (!isset($_GET['course_id'])) {
    echo "<script>alert('Invalid course ID!'); window.location.href='assignment_list.php';</script>";
    exit();
}

$course_id = intval($_GET['course_id']);

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $title = trim($_POST['title']);
    $description = trim($_POST['description']);
    $due_date = trim($_POST['due_date']);

    // Validate input
    if (empty($title) || empty($description) || empty($due_date)) {
        $error = "All fields are required.";
    } else {
        // Insert the assignment into the database
        $stmt = $conn->prepare("INSERT INTO assignments (title, description, due_date, course_id) VALUES (?, ?, ?, ?)");
        $stmt->bind_param("sssi", $title, $description, $due_date, $course_id);

        if ($stmt->execute()) {
            header("Location: assignment_list.php?course_id=" . $course_id);
            exit();
        } else {
            $error = "Error creating assignment. Please try again.";
        }
    }
}
?>

<div class="container">
    <h2>Create New Assignment for Course ID: <?php echo htmlspecialchars($course_id); ?></h2>

    <?php if (isset($error)): ?>
        <div class="alert alert-danger"><?php echo htmlspecialchars($error); ?></div>
    <?php endif; ?>

    <form action="" method="POST">
        <div class="form-group">
            <label for="title">Assignment Title</label>
            <input type="text" class="form-control" id="title" name="title" required>
        </div>
        <div class="form-group">
            <label for="description">Description</label>
            <textarea class="form-control" id="description" name="description" rows="4" required></textarea>
        </div>
        <div class="form-group">
            <label for="due_date">Due Date</label>
            <input type="date" class="form-control" id="due_date" name="due_date" required>
        </div>
        <button type="submit" class="btn btn-primary">Create Assignment</button>
        <a href="assignment_list.php?course_id=<?php echo $course_id; ?>" class="btn btn-secondary">Cancel</a>
    </form>
</div>

<?php include '../layouts/footer.php'; // Include footer ?>

Explanation of assignment_create.php
  1. Session Management: The script starts a session and checks if the user is logged in. If not, it redirects the user to the login page.
  2. Check Course ID: It validates if the course_id is provided in the URL. If not, it shows an alert and redirects the user back to the assignment list.
  3. Form Submission Handling:Checks if the request method is POST, indicating that the form has been submitted.
  4. Retrieves and trims the title, description, and due_date from the form input.
  5. Validates that none of the fields are empty.
  6. If valid, it prepares and executes an SQL statement to insert the new assignment into the assignments table in the database.
  7. If the insertion is successful, it redirects to the assignment_list.php page for the associated course.
  8. If there is an error during insertion, it sets an error message to be displayed to the user.
  9. HTML Structure:Displays a header showing the course ID for which the assignment is being created.
  10. Includes a form with input fields for the assignment title, description, and due date, using Bootstrap for styling.
  11. Contains a submit button to create the assignment and a cancel button to go back to the assignment list.
Summary
The assignment_create.php file provides a user-friendly interface for creating a new assignment associated with a specific course. 

16. views/assignments/assignment_view.php

This file displays the details of a specific assignment, including its title, description, due date, and any associated submissions.

<?php
session_start();
include '../../config.php'; // Include database connection
include '../layouts/header.php'; // Include header
include '../layouts/sidebar.php'; // Include sidebar

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header("Location: ../auth/login.php");
    exit();
}

// Check if assignment ID is provided
if (!isset($_GET['id'])) {
    echo "<script>alert('Invalid assignment ID!'); window.location.href='assignment_list.php';</script>";
    exit();
}

$assignment_id = intval($_GET['id']);

// Fetch assignment details
$stmt = $conn->prepare("SELECT * FROM assignments WHERE id = ?");
$stmt->bind_param("i", $assignment_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows == 0) {
    echo "<script>alert('Assignment not found!'); window.location.href='assignment_list.php';</script>";
    exit();
}

$assignment = $result->fetch_assoc();

// Fetch submissions for the assignment
$stmt = $conn->prepare("SELECT * FROM submissions WHERE assignment_id = ?");
$stmt->bind_param("i", $assignment_id);
$stmt->execute();
$submissions = $stmt->get_result();
?>

<div class="container">
    <h2>Assignment Details</h2>
    <h3><?php echo htmlspecialchars($assignment['title']); ?></h3>
    <p><strong>Description:</strong> <?php echo nl2br(htmlspecialchars($assignment['description'])); ?></p>
    <p><strong>Due Date:</strong> <?php echo htmlspecialchars($assignment['due_date']); ?></p>
    <p><strong>Course ID:</strong> <?php echo htmlspecialchars($assignment['course_id']); ?></p>

    <h4>Submissions:</h4>
    <table class="table table-bordered">
        <thead>
            <tr>
                <th>ID</th>
                <th>User ID</th>
                <th>Submission Date</th>
                <th>Comments</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php if ($submissions->num_rows > 0): ?>
                <?php while ($submission = $submissions->fetch_assoc()): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($submission['id']); ?></td>
                        <td><?php echo htmlspecialchars($submission['user_id']); ?></td>
                        <td><?php echo htmlspecialchars($submission['submission_date']); ?></td>
                        <td><?php echo nl2br(htmlspecialchars($submission['comments'])); ?></td>
                        <td>
                            <a href="submission_view.php?id=<?php echo $submission['id']; ?>" class="btn btn-info btn-sm">View</a>
                        </td>
                    </tr>
                <?php endwhile; ?>
            <?php else: ?>
                <tr>
                    <td colspan="5" class="text-center">No submissions found for this assignment.</td>
                </tr>
            <?php endif; ?>
        </tbody>
    </table>

    <a href="assignment_list.php?course_id=<?php echo $assignment['course_id']; ?>" class="btn btn-secondary">Back to Assignments</a>
</div>

<?php include '../layouts/footer.php'; // Include footer ?>

Explanation of assignment_view.php

  1. Session Management: Starts a session and checks if the user is logged in. If not, it redirects them to the login page.
  2. Check Assignment ID: Validates if the id of the assignment is provided in the URL. If not, it shows an alert and redirects the user back to the assignment list.
  3. Fetch Assignment Details:Prepares and executes a SQL statement to fetch details of the specified assignment using the assignment ID.
  4. If no assignment is found, it alerts the user and redirects back to the assignment list.
  5. Fetch Submissions:Prepares and executes a SQL statement to fetch submissions related to the assignment.
  6. The submissions are stored in a variable for later display.
  7. HTML Structure:Displays the title, description, due date, and associated course ID of the assignment.
  8. Includes a table that lists all submissions for the assignment, displaying their ID, user ID, submission date, comments, and actions.
  9. If there are no submissions, it displays a message indicating that no submissions are found.
  10. Action Buttons:Each submission row contains a button to view more details about that submission, linking to the submission_view.php page with the submission ID.
  11. Back Button: Provides a button to return to the assignment list for the associated course.

Summary
The assignment_view.php file allows users to view detailed information about a specific assignment and any submissions related to it. 

17. views/quizzes/quiz_list.php

This file lists all the quizzes associated with a specific course and allows the user to view, create, and edit quizzes.

<?php
session_start();
include '../../config.php'; // Include database connection
include '../layouts/header.php'; // Include header
include '../layouts/sidebar.php'; // Include sidebar

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header("Location: ../auth/login.php");
    exit();
}

// Check if course ID is provided
if (!isset($_GET['course_id'])) {
    echo "<script>alert('Invalid course ID!'); window.location.href='../courses/course_list.php';</script>";
    exit();
}

$course_id = intval($_GET['course_id']);

// Fetch quizzes for the specified course
$stmt = $conn->prepare("SELECT * FROM quizzes WHERE course_id = ?");
$stmt->bind_param("i", $course_id);
$stmt->execute();
$result = $stmt->get_result();
?>

<div class="container">
    <h2>Quizzes for Course ID: <?php echo htmlspecialchars($course_id); ?></h2>
    <a href="quiz_create.php?course_id=<?php echo $course_id; ?>" class="btn btn-primary">Create New Quiz</a>
    <table class="table table-bordered">
        <thead>
            <tr>
                <th>ID</th>
                <th>Title</th>
                <th>Description</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php if ($result->num_rows > 0): ?>
                <?php while ($quiz = $result->fetch_assoc()): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($quiz['id']); ?></td>
                        <td><?php echo htmlspecialchars($quiz['title']); ?></td>
                        <td><?php echo nl2br(htmlspecialchars($quiz['description'])); ?></td>
                        <td>
                            <a href="quiz_view.php?id=<?php echo $quiz['id']; ?>" class="btn btn-info btn-sm">View</a>
                            <a href="quiz_edit.php?id=<?php echo $quiz['id']; ?>" class="btn btn-warning btn-sm">Edit</a>
                            <a href="quiz_delete.php?id=<?php echo $quiz['id']; ?>" class="btn btn-danger btn-sm" onclick="return confirm('Are you sure you want to delete this quiz?');">Delete</a>
                        </td>
                    </tr>
                <?php endwhile; ?>
            <?php else: ?>
                <tr>
                    <td colspan="4" class="text-center">No quizzes found for this course.</td>
                </tr>
            <?php endif; ?>
        </tbody>
    </table>
    <a href="../courses/course_view.php?id=<?php echo $course_id; ?>" class="btn btn-secondary">Back to Course</a>
</div>

<?php include '../layouts/footer.php'; // Include footer ?>
Explanation of quiz_list.php
  1. Session Management: Starts a session and checks if the user is logged in. If not, it redirects them to the login page.
  2. Check Course ID: Validates if the course_id is provided in the URL. If not, it shows an alert and redirects the user back to the course list.
  3. Fetch Quizzes:Prepares and executes a SQL statement to fetch all quizzes associated with the specified course using the course ID.
  4. The result is stored in a variable for later display.
  5. HTML Structure:Displays the course ID for which quizzes are listed.
  6. Includes a button to create a new quiz, linking to quiz_create.php with the course ID.
  7. Presents a table that lists all quizzes for the course, displaying their ID, title, description, and actions.
  8. Action Buttons:Each quiz row contains buttons to view, edit, or delete the quiz. The delete button includes a confirmation prompt to prevent accidental deletions.
  9. No Quizzes Message: If no quizzes are found for the course, it displays a message indicating that no quizzes are available.
  10. Back Button: Provides a button to return to the course view page.

Summary
The quiz_list.php file allows users to manage quizzes related to a specific course effectively.

17.views/quizzes/quiz_create.php

This file allows users to create a new quiz for a specific course.

<?php
session_start();
include '../../config.php'; // Include database connection
include '../layouts/header.php'; // Include header
include '../layouts/sidebar.php'; // Include sidebar

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header("Location: ../auth/login.php");
    exit();
}

// Check if course ID is provided
if (!isset($_GET['course_id'])) {
    echo "<script>alert('Invalid course ID!'); window.location.href='../courses/course_list.php';</script>";
    exit();
}

$course_id = intval($_GET['course_id']);

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $title = $_POST['title'];
    $description = $_POST['description'];

    // Insert new quiz into the database
    $stmt = $conn->prepare("INSERT INTO quizzes (course_id, title, description) VALUES (?, ?, ?)");
    $stmt->bind_param("iss", $course_id, $title, $description);

    if ($stmt->execute()) {
        echo "<script>alert('Quiz created successfully!'); window.location.href='quiz_list.php?course_id=$course_id';</script>";
    } else {
        echo "<script>alert('Error creating quiz: " . $stmt->error . "');</script>";
    }
}
?>

<div class="container">
    <h2>Create New Quiz for Course ID: <?php echo htmlspecialchars($course_id); ?></h2>
    <form method="POST" action="">
        <div class="form-group">
            <label for="title">Title</label>
            <input type="text" class="form-control" id="title" name="title" required>
        </div>
        <div class="form-group">
            <label for="description">Description</label>
            <textarea class="form-control" id="description" name="description" rows="5" required></textarea>
        </div>
        <button type="submit" class="btn btn-primary">Create Quiz</button>
        <a href="quiz_list.php?course_id=<?php echo $course_id; ?>" class="btn btn-secondary">Cancel</a>
    </form>
</div>

<?php include '../layouts/footer.php'; // Include footer ?>

Explanation of quiz_create.php
  1. Session Management: Starts a session and checks if the user is logged in. If not, it redirects them to the login page.
  2. Check Course ID: Validates if the course_id is provided in the URL. If not, it shows an alert and redirects the user back to the course list.
  3. Handle Form Submission:Checks if the form is submitted via a POST request.
  4. Retrieves the quiz title and description from the form.
  5. Prepares and executes a SQL statement to insert the new quiz into the quizzes table associated with the specified course ID.
  6. If the quiz is created successfully, it alerts the user and redirects them to the quiz list page for that course. If there is an error, it alerts the user with the error message.
  7. HTML Structure:Displays a form for creating a new quiz, including fields for the quiz title and description.
  8. The form uses the POST method to submit the data back to the same page.
  9. Buttons:A button to submit the form for creating the quiz.
  10. A cancel button that redirects back to the quiz list for the specified course.
Summary
The quiz_create.php file allows users to create a new quiz for a specific course easily.

18. views/quizzes/quiz_view.php

This file allows users to view the details of a specific quiz and see the questions associated with it.

<?php
session_start();
include '../../config.php'; // Include database connection
include '../layouts/header.php'; // Include header
include '../layouts/sidebar.php'; // Include sidebar

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header("Location: ../auth/login.php");
    exit();
}

// Check if quiz ID is provided
if (!isset($_GET['id'])) {
    echo "<script>alert('Invalid quiz ID!'); window.location.href='quiz_list.php';</script>";
    exit();
}

$quiz_id = intval($_GET['id']);

// Fetch quiz details
$stmt = $conn->prepare("SELECT * FROM quizzes WHERE id = ?");
$stmt->bind_param("i", $quiz_id);
$stmt->execute();
$result = $stmt->get_result();
$quiz = $result->fetch_assoc();

// Check if quiz exists
if (!$quiz) {
    echo "<script>alert('Quiz not found!'); window.location.href='quiz_list.php';</script>";
    exit();
}

// Fetch questions associated with the quiz
$stmt = $conn->prepare("SELECT * FROM questions WHERE quiz_id = ?");
$stmt->bind_param("i", $quiz_id);
$stmt->execute();
$questions_result = $stmt->get_result();
?>

<div class="container">
    <h2>Quiz: <?php echo htmlspecialchars($quiz['title']); ?></h2>
    <p><strong>Description:</strong> <?php echo nl2br(htmlspecialchars($quiz['description'])); ?></p>

    <h3>Questions:</h3>
    <table class="table table-bordered">
        <thead>
            <tr>
                <th>ID</th>
                <th>Question</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php if ($questions_result->num_rows > 0): ?>
                <?php while ($question = $questions_result->fetch_assoc()): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($question['id']); ?></td>
                        <td><?php echo nl2br(htmlspecialchars($question['question'])); ?></td>
                        <td>
                            <a href="question_edit.php?id=<?php echo $question['id']; ?>" class="btn btn-warning btn-sm">Edit</a>
                            <a href="question_delete.php?id=<?php echo $question['id']; ?>" class="btn btn-danger btn-sm" onclick="return confirm('Are you sure you want to delete this question?');">Delete</a>
                        </td>
                    </tr>
                <?php endwhile; ?>
            <?php else: ?>
                <tr>
                    <td colspan="3" class="text-center">No questions found for this quiz.</td>
                </tr>
            <?php endif; ?>
        </tbody>
    </table>

    <a href="quiz_edit.php?id=<?php echo $quiz_id; ?>" class="btn btn-warning">Edit Quiz</a>
    <a href="quiz_list.php?course_id=<?php echo $quiz['course_id']; ?>" class="btn btn-secondary">Back to Quizzes</a>
</div>

<?php include '../layouts/footer.php'; // Include footer ?>

Explanation of quiz_view.php
  1. Session Management: Starts a session and checks if the user is logged in. If not, it redirects them to the login page.
  2. Check Quiz ID: Validates if the id of the quiz is provided in the URL. If not, it shows an alert and redirects the user back to the quiz list.
  3. Fetch Quiz Details:Prepares and executes a SQL statement to fetch the details of the quiz using its ID.
  4. Checks if the quiz exists in the database. If not, it alerts the user and redirects them back to the quiz list.
  5. Fetch Associated Questions:Executes another SQL statement to fetch all questions associated with the quiz.
  6. HTML Structure:isplays the quiz title and description.
  7. Lists all questions associated with the quiz in a table format, including their IDs and actions for editing or deleting each question.
  8. Action Buttons:Provides buttons for editing the quiz and going back to the quiz list for the corresponding course.
  9. No Questions Message: If no questions are found for the quiz, it displays a message indicating that no questions are available.

Summary
The quiz_view.php file allows users to view the details of a specific quiz, including its questions and options for editing or deleting those questions. 
You said:
views/notifications/notifications.php
ChatGPT said:

19.views/notifications/notifications.php

 This file allows users to view their notifications, which could include updates on assignments, quizzes, or any other relevant messages.

<?php
session_start();
include '../../config.php'; // Include database connection
include '../layouts/header.php'; // Include header
include '../layouts/sidebar.php'; // Include sidebar

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header("Location: ../auth/login.php");
    exit();
}

// Fetch notifications for the logged-in user
$user_id = $_SESSION['user_id'];
$stmt = $conn->prepare("SELECT * FROM notifications WHERE user_id = ? ORDER BY created_at DESC");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();
?>

<div class="container">
    <h2>Your Notifications</h2>
    <?php if ($result->num_rows > 0): ?>
        <table class="table table-bordered">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Message</th>
                    <th>Created At</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php while ($notification = $result->fetch_assoc()): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($notification['id']); ?></td>
                        <td><?php echo nl2br(htmlspecialchars($notification['message'])); ?></td>
                        <td><?php echo date('Y-m-d H:i:s', strtotime($notification['created_at'])); ?></td>
                        <td>
                            <a href="notification_delete.php?id=<?php echo $notification['id']; ?>" class="btn btn-danger btn-sm" onclick="return confirm('Are you sure you want to delete this notification?');">Delete</a>
                        </td>
                    </tr>
                <?php endwhile; ?>
            </tbody>
        </table>
    <?php else: ?>
        <p>No notifications found.</p>
    <?php endif; ?>
</div>

<?php include '../layouts/footer.php'; // Include footer ?>

Explanation of notifications.php

  1. Session Management: Starts a session and checks if the user is logged in. If not, it redirects them to the login page.
  2. Fetch Notifications:Retrieves the user ID from the session.
  3. Prepares and executes a SQL statement to fetch notifications for the logged-in user, ordering them by creation date in descending order.
  4. HTML Structure:Displays a heading for the notifications.
  5. If notifications exist, it lists them in a table format with their ID, message, creation date, and an action button for deleting each notification.
  6. If no notifications are found, it displays a message indicating that there are no notifications available.
  7. Action Buttons:Provides a delete button for each notification, which will prompt the user for confirmation before deleting.
Summary
The notifications.php file provides users with an overview of their notifications, allowing them to keep track of important messages related to their courses and assignments. 

index.php
 This file serves as the main entry point for your application, directing users to either the login or registration page based on their authentication status.

<?php
session_start();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Online Learning Platform</title>
    <link rel="stylesheet" href="assets/css/styles.css"> <!-- Link to CSS styles -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
    <div class="container text-center">
        <h1 class="mt-5">Welcome to the Online Learning Platform</h1>
        <p class="lead">Your gateway to knowledge and education.</p>

        <?php if (isset($_SESSION['user_id'])): ?>
            <a href="views/dashboard/dashboard.php" class="btn btn-primary">Go to Dashboard</a>
        <?php else: ?>
            <div class="mt-4">
                <a href="views/auth/login.php" class="btn btn-success">Login</a>
                <a href="views/auth/register.php" class="btn btn-secondary">Register</a>
            </div>
        <?php endif; ?>
    </div>

    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.0.7/dist/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>
</html>
Explanation of index.php
Session Management: Starts a session to maintain user authentication status.

HTML Structure:

Uses Bootstrap for responsive design.
Contains a welcoming message and a brief description of the platform.
Conditional Content:

If the user is logged in (checked using $_SESSION['user_id']), it provides a button to go to the dashboard.
If the user is not logged in, it displays buttons for the Login and Registration pages.
Styles and Scripts:

Links to a custom CSS file for additional styling and includes Bootstrap's CSS and JavaScript libraries for layout and interactivity.
Summary
The index.php file serves as the landing page for your Online Learning Platform, guiding users to either their dashboard or the authentication pages (login/registration). 

The .htaccess file is an important configuration file used by Apache web servers to manage various settings, such as URL rewriting, access control, and more. For your Online Learning Platform project, a typical .htaccess file might include rules for friendly URLs, security settings, and redirection. 

.htaccess File

# Enable URL rewriting
RewriteEngine On

# Redirect to the index.php for all requests not pointing to a file or directory
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [L]

# Prevent directory listing
Options -Indexes

# Protect sensitive files and directories
<FilesMatch "\.(htaccess|ini|phps|php|env)$">
    Order Allow,Deny
    Deny from all
</FilesMatch>

# Redirect www to non-www (optional)
# RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
# RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

# Set the default character set
AddDefaultCharset UTF-8

# Custom error pages
ErrorDocument 404 /views/errors/404.php
ErrorDocument 500 /views/errors/500.php

Explanation of .htaccess Rules
  1. Enable URL Rewriting: The RewriteEngine On directive enables the rewriting engine, allowing you to create cleaner, more readable URLs.
  2. Redirect Requests:The RewriteCond directives check if the requested filename is not a file (!-f) and not a directory (!-d). If both conditions are met, it rewrites the URL to index.php.
  3. This allows you to handle all incoming requests through index.php, which is useful for routing in a single-page application.
  4. Prevent Directory Listing: The Options -Indexes directive disables directory listing if the requested directory does not contain an index file.
  5. Protect Sensitive Files: The <FilesMatch> directive restricts access to sensitive files (like .htaccess, .ini, and .env) by denying access to everyone.
  6. Redirect www to non-www: The commented-out section provides an option to redirect users from the www subdomain to the non-www version of your site. You can uncomment this section if you prefer this behavior.
  7. Set Default Character Set: The AddDefaultCharset UTF-8 directive sets the default character encoding for the website to UTF-8.
  8. Custom Error Pages: The ErrorDocument directives specify custom error pages for 404 (Not Found) and 500 (Internal Server Error) responses.

Summary
The .htaccess file is a powerful tool for configuring your Apache server settings, enhancing security, and creating user-friendly URLs. Adjust the rules based on your specific requirements and server configuration. 



Post a Comment

0Comments

Post a Comment (0)