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
- Constructor: Accepts a database connection (assumed to be a PDO instance) for database operations.
- 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.
- Authenticate Method: Checks if the user exists by email and verifies the password. Returns the user data if authentication is successful.
- Get User By ID Method: Fetches user details based on the user ID.
- Update User Method: Updates user information. If a new password is provided, it will update that as well.
- Get All Users Method: Retrieves all users from the database (this can be used by an admin to view all users).
- 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
- Constructor: Accepts a database connection (assumed to be a PDO instance) for database operations.
- Create Course Method: Takes course details (title, description, instructor ID, and creation date) and inserts a new course into the courses table.
- Get All Courses Method: Fetches all courses from the database.
- Get Course By ID Method: Fetches a course's details based on the course ID.
- Update Course Method: Updates a course's title and description based on the course ID.
- Delete Course Method: Deletes a course based on the course ID.
- 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
- Constructor: Accepts a database connection (assumed to be a PDO instance) for database operations.
- Create Module Method: Takes module details (course ID, title, description, and creation date) and inserts a new module into the modules table.
- Get Modules By Course ID Method: Fetches all modules associated with a specific course based on the course ID.
- Get Module By ID Method: Fetches the details of a specific module based on the module ID.
- Update Module Method: Updates a module's title and description based on the module ID.
- 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
- Constructor: Accepts a database connection (assumed to be a PDO instance) for database operations.
- Create Assignment Method: Takes assignment details (module ID, title, description, due date, and creation date) and inserts a new assignment into the assignments table.
- Get Assignments By Module ID Method: Fetches all assignments associated with a specific module based on the module ID.
- Get Assignment By ID Method: Fetches the details of a specific assignment based on the assignment ID.
- Update Assignment Method: Updates an assignment's title, description, and due date based on the assignment ID.
- Delete Assignment Method: Deletes an assignment based on the assignment ID.
- 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
- Constructor: Accepts a database connection (assumed to be a PDO instance) for database operations.
- Create Quiz Method: Takes quiz details (module ID, title, description, and creation date) and inserts a new quiz into the quizzes table.
- Get Quizzes By Module ID Method: Fetches all quizzes associated with a specific module based on the module ID.
- Get Quiz By ID Method: Fetches the details of a specific quiz based on the quiz ID.
- Update Quiz Method: Updates a quiz's title and description based on the quiz ID.
- Delete Quiz Method: Deletes a quiz based on the quiz ID.
- Create Question Method: Inserts a new question for a quiz, including options and the correct answer.
- Get Questions By Quiz ID Method: Fetches all questions associated with a specific quiz.
- 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
- Constructor: Accepts a database connection (assumed to be a PDO instance) for database operations.
- Create Submission Method: Takes details about the user, assignment ID, submission content, and submission time, and inserts a new submission into the submissions table.
- Get Submissions By Assignment ID Method: Fetches all submissions associated with a specific assignment based on the assignment ID.
- Get Submission By ID Method: Fetches the details of a specific submission based on the submission ID.
- Update Submission Method: Updates a submission's content based on the submission ID.
- Delete Submission Method: Deletes a submission based on the submission ID.
- 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
- Constructor: Accepts a database connection (assumed to be a PDO instance) for database operations.
- Create Notification Method: Takes details about the user, notification message, type, and creation time, and inserts a new notification into the notifications table.
- 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).
- Get Notification By ID Method: Fetches the details of a specific notification based on the notification ID.
- Mark As Read Method: Updates a notification to mark it as read based on the notification ID.
- 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
- Constructor: Accepts a database connection (assumed to be a PDO instance) for database operations.
- Enroll User in Course Method: Inserts a new enrollment record into the enrollments table, linking a user to a specific course.
- Get Enrollments By User ID Method: Retrieves all enrollments for a specific user, including course titles, ordered by enrollment date.
- Get Users By Course ID Method: Fetches all users enrolled in a specific course, including user names.
- Is User Enrolled Method: Checks if a specific user is already enrolled in a specific course.
- 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
- DOCTYPE and HTML Structure: Defines the document type and sets up the basic HTML structure, including language and character encoding.
- Head Section:
- Meta Tags: Provides character set and viewport settings for responsive design.
- Title: Sets the page title, which can be dynamic based on the $title variable passed from the controller.
- CSS Link: Includes the main stylesheet for the platform.
- JavaScript Link: Links to the main JavaScript file and defers its execution until the HTML is parsed.
- Header Section: Contains the main navigation and branding for the platform.
- Logo/Title: A clickable title that redirects to the home page.
- Navigation Menu:
- Links to various sections of the platform, including courses, assignments, quizzes, and notifications.
- Conditional rendering of user-related links based on whether a user is logged in or not.
- If the user is logged in, links to the profile and logout options are displayed.
- 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>© <?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
- Footer Section: This contains important information and links relevant to the users of the platform.
- Copyright Notice: Dynamically generated using PHP's date() function to always display the current year, along with the name of the platform.
- Additional Links: Provides links to important pages such as Privacy Policy, Terms of Service, and Contact Us.
- 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
- Sidebar Section: This section is designed to facilitate navigation for users, particularly those with administrative privileges.
- Dashboard Title: The title indicates that this sidebar is part of the dashboard area.
- Navigation Links: Contains links for:
- Managing courses
- Managing assignments
- Managing quizzes
- Viewing notifications
- Managing users (for admin users)
- 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
- Session Management: Starts a session to track user authentication.
- Header Inclusion: Includes the header layout at the top of the page.
- Redirect if Logged In: If the user is already logged in, they are redirected to the dashboard.
- Form Handling:Initializes variables to store email, password, and any error messages.
- Checks if the request method is POST (form submission).
- Retrieves and trims the input data for email and password.
- Validates the input to ensure both fields are filled.
- Prepares and executes a SQL statement to fetch the user by email.
- If a user is found, it verifies the password using password_verify().
- If the credentials are valid, it stores the user ID, name, and role in session variables and redirects to the dashboard.
- If not, it sets an error message indicating invalid credentials.
- 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
- Session Management: Starts a session to handle user registrations.
- Header Inclusion: Includes the header layout at the top of the page.
- Form Handling:Initializes variables to store name, email, password, confirm password, and any error messages.
- Checks if the request method is POST (form submission).
- Retrieves and trims the input data for name, email, password, and confirm password.
- Validates the input:Ensures all fields are filled.
- Validates the email format.Checks if the passwords match.
- Checks if the email already exists in the database. If it does, it sets an error message.
- If the email is unique, it hashes the password using password_hash().
- Inserts the new user into the users table with a default role of 'student' and the current timestamp.
- On successful registration, it redirects the user to the login page.
- 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
- Session Management: Starts a session and checks if the user is logged in. If not, it redirects them to the login page.
- Header and Sidebar Inclusion: Includes the header and sidebar layouts.
- Fetch User Information: Retrieves the logged-in user’s name and email from the users table based on their user ID.
- Fetch Enrolled Courses: Retrieves the courses the user is enrolled in by joining the courses and enrollments tables.
- Fetch Assignments: Retrieves assignments associated with the user’s enrolled courses, ordered by due date.
- Fetch Quizzes: Retrieves quizzes associated with the user’s enrolled courses.
- Fetch Notifications: Retrieves notifications for the user, ordered by the created date.
- HTML Structure:Displays a welcome message to the user.
- Lists the user's enrolled courses, assignments (with due dates), quizzes, and notifications.
- 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
- Session Management: Starts a session and checks if the user is logged in. If not, it redirects them to the login page.
- Header and Sidebar Inclusion: Includes the header and sidebar layouts.
- Fetch Courses: Prepares and executes a SQL statement to fetch all courses from the courses table, retrieving the course ID, title, and description.
- HTML Structure:Displays a title for the courses section.
- Utilizes a table to list the courses.
- For each course, it shows the title, description, and action buttons:
- View: Links to a course detail page (assuming it will be implemented in view.php).
- 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
- 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.
- Form Handling:If the form is submitted via a POST request, it retrieves the course title and description from the form inputs.
- Prepares and executes a SQL statement to insert the new course into the courses table.
- Displays an alert message to inform the user whether the course was created successfully or if there was an error.
- HTML Form:Contains a form for creating a new course, including fields for the course title and description.
- 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
- 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.
- Fetch Course Details:Retrieves the course ID from the URL.
- Prepares and executes a SQL statement to fetch the course's current title and description from the courses table.
- If the course is not found, it alerts the user and redirects them to the course list.
- Form Handling:If the form is submitted via a POST request, it retrieves the updated course title and description.
- Prepares and executes a SQL statement to update the course details in the courses table.
- Displays an alert message to inform the user whether the course was updated successfully or if there was an error.
- HTML Form:Contains a form for editing the course, pre-filling the title and description fields with the current values.
- 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
- Session Management: Starts a session and checks if the user is logged in. If not, it redirects them to the login page.
- Fetch Course Details:Retrieves the course ID from the URL.
- Prepares and executes a SQL statement to fetch the course's title and description from the courses table.
- If the course is not found, it alerts the user and redirects them to the course list.
- Fetch Related Data:Retrieves modules, assignments, and quizzes associated with the course by executing separate SQL statements for each.
- Each statement binds the course_id to filter the results accordingly.
- Display Course Details:Displays the course title and description.
- 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).
- 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
- Session Management: Starts a session and checks if the user is logged in. If not, it redirects them to the login page.
- Fetch Course ID: Retrieves the course ID from the URL to display the modules for that specific course.
- Fetch Course Details:Prepares and executes a SQL statement to get the course title based on the course_id.
- If the course is not found, it alerts the user and redirects them to the course list.
- Fetch Modules:Prepares and executes a SQL statement to fetch all modules related to the specified course.
- Display Modules:Displays a list of modules in a table format.
- Each module has options to view, edit, or delete.
- Add New Module: Provides a button to navigate to the module creation page (module_create.php).
- 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
- Session Management: Starts a session and checks if the user is logged in. If not, it redirects them to the login page.
- 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.
- Form Submission Handling:Checks if the request method is POST, indicating that the form has been submitted.
- Retrieves and trims the title and description from the form input.
- Validates that both fields are not empty.
- If valid, it prepares and executes an SQL statement to insert the new module into the modules table.
- If the insertion is successful, it redirects to the module_list.php page for the course.
- If there's an error, it sets an error message to be displayed to the user.
- 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
- Session Management: Starts a session and checks if the user is logged in. If not, it redirects them to the login page.
- 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.
- 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.
- If no module is found, it alerts the user and redirects them back to the module list.
- Form Submission Handling:Checks if the request method is POST, indicating that the form has been submitted.
- Retrieves and trims the title and description from the form input.
- Validates that both fields are not empty.
- If valid, it prepares and executes an SQL statement to update the existing module in the modules table.
- If the update is successful, it redirects to the module_list.php page for the associated course.
- If there's an error, it sets an error message to be displayed to the user.
- HTML Form Structure:Utilizes Bootstrap for styling the layout.
- Contains input fields pre-filled with the existing module title and description.
- 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
- Session Management: Starts a session and checks if the user is logged in. If not, it redirects them to the login page.
- 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.
- Fetch Assignments:Prepares and executes a SQL statement to fetch all assignments associated with the provided course ID.
- The result is stored in $result.
- HTML Structure:Displays a header showing the course ID for which the assignments are being listed.
- Includes a button to create a new assignment, which links to the assignment_create.php file with the course ID as a query parameter.
- Uses a Bootstrap-styled table to display the list of assignments, including their ID, title, description, due date, and actions (Edit and Delete).
- If there are no assignments, it shows a message indicating that no assignments are found.
- Action Buttons:Each assignment row contains two action buttons:
- Edit: Links to the assignment_edit.php page with the assignment ID and course ID.
- 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
- 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.
- 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.
- Form Submission Handling:Checks if the request method is POST, indicating that the form has been submitted.
- Retrieves and trims the title, description, and due_date from the form input.
- Validates that none of the fields are empty.
- If valid, it prepares and executes an SQL statement to insert the new assignment into the assignments table in the database.
- If the insertion is successful, it redirects to the assignment_list.php page for the associated course.
- If there is an error during insertion, it sets an error message to be displayed to the user.
- HTML Structure:Displays a header showing the course ID for which the assignment is being created.
- Includes a form with input fields for the assignment title, description, and due date, using Bootstrap for styling.
- 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
- Session Management: Starts a session and checks if the user is logged in. If not, it redirects them to the login page.
- 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.
- Fetch Assignment Details:Prepares and executes a SQL statement to fetch details of the specified assignment using the assignment ID.
- If no assignment is found, it alerts the user and redirects back to the assignment list.
- Fetch Submissions:Prepares and executes a SQL statement to fetch submissions related to the assignment.
- The submissions are stored in a variable for later display.
- HTML Structure:Displays the title, description, due date, and associated course ID of the assignment.
- Includes a table that lists all submissions for the assignment, displaying their ID, user ID, submission date, comments, and actions.
- If there are no submissions, it displays a message indicating that no submissions are found.
- 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.
- 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
- Session Management: Starts a session and checks if the user is logged in. If not, it redirects them to the login page.
- 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.
- Fetch Quizzes:Prepares and executes a SQL statement to fetch all quizzes associated with the specified course using the course ID.
- The result is stored in a variable for later display.
- HTML Structure:Displays the course ID for which quizzes are listed.
- Includes a button to create a new quiz, linking to quiz_create.php with the course ID.
- Presents a table that lists all quizzes for the course, displaying their ID, title, description, and actions.
- 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.
- No Quizzes Message: If no quizzes are found for the course, it displays a message indicating that no quizzes are available.
- 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
- Session Management: Starts a session and checks if the user is logged in. If not, it redirects them to the login page.
- 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.
- Handle Form Submission:Checks if the form is submitted via a POST request.
- Retrieves the quiz title and description from the form.
- Prepares and executes a SQL statement to insert the new quiz into the quizzes table associated with the specified course ID.
- 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.
- HTML Structure:Displays a form for creating a new quiz, including fields for the quiz title and description.
- The form uses the POST method to submit the data back to the same page.
- Buttons:A button to submit the form for creating the quiz.
- 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
- Session Management: Starts a session and checks if the user is logged in. If not, it redirects them to the login page.
- 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.
- Fetch Quiz Details:Prepares and executes a SQL statement to fetch the details of the quiz using its ID.
- Checks if the quiz exists in the database. If not, it alerts the user and redirects them back to the quiz list.
- Fetch Associated Questions:Executes another SQL statement to fetch all questions associated with the quiz.
- HTML Structure:isplays the quiz title and description.
- Lists all questions associated with the quiz in a table format, including their IDs and actions for editing or deleting each question.
- Action Buttons:Provides buttons for editing the quiz and going back to the quiz list for the corresponding course.
- 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
- Session Management: Starts a session and checks if the user is logged in. If not, it redirects them to the login page.
- Fetch Notifications:Retrieves the user ID from the session.
- Prepares and executes a SQL statement to fetch notifications for the logged-in user, ordering them by creation date in descending order.
- HTML Structure:Displays a heading for the notifications.
- If notifications exist, it lists them in a table format with their ID, message, creation date, and an action button for deleting each notification.
- If no notifications are found, it displays a message indicating that there are no notifications available.
- 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
- Enable URL Rewriting: The RewriteEngine On directive enables the rewriting engine, allowing you to create cleaner, more readable URLs.
- 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.
- This allows you to handle all incoming requests through index.php, which is useful for routing in a single-page application.
- Prevent Directory Listing: The Options -Indexes directive disables directory listing if the requested directory does not contain an index file.
- Protect Sensitive Files: The <FilesMatch> directive restricts access to sensitive files (like .htaccess, .ini, and .env) by denying access to everyone.
- 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.
- Set Default Character Set: The AddDefaultCharset UTF-8 directive sets the default character encoding for the website to UTF-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.