Question One
A university plans to develop a course registration system to manage students and courses.
Each student has a registration number, name, and email address, while each course has a course code, course name, and credit value. A student may register for multiple courses. You are required to design a Student class and a Course class using proper encapsulation principles, create a Database class that manages the database connection using PDO, implement a method that allows a student to register for a course and stores this information in the database, and write a PHP script that retrieves and displays all courses registered by a specific student.
(20 Marks)
Answer(Click to Show)
The system includes the following components: i. Student Class
- Stores student information:
- Registration Number
- Name
ii. Course Class
- Stores course information:
- Course Code
- Course Name
- Credit Value
iii. Database Class
- Handles database connection using PDO (PHP Data Objects).
iv. Registration Function
- Allows a student to register for courses and store this relationship in the database.
v. Retrieval Script
- Displays all courses registered by a specific student.
<?php
//1. DATABASE CLASS (Database.php)
// Manages database connection using PDO
class Database {
private $host = "localhost";
private $dbname = "university_db";
private $username = "root";
private $password = "";
private $pdo;
// Constructor establishes database connection
public function __construct(){
try{
// Create PDO connection
$this->pdo = new PDO(
"mysql:host=".$this->host.";dbname=".$this->dbname,
$this->username,
$this->password
);
// Enable PDO error reporting
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
// Display error if connection fails
echo "Database connection failed: " . $e->getMessage();
}
}
// Method returns database connection
public function getConnection(){
return $this->pdo;
}
}
//2. STUDENT CLASS (Student.php)
// Demonstrates encapsulation
class Student {
// Private properties
private $regNumber;
private $name;
private $email;
// Constructor initializes student data
public function __construct($regNumber, $name, $email){
$this->regNumber = $regNumber;
$this->name = $name;
$this->email = $email;
}
// Getter methods
public function getRegNumber(){
return $this->regNumber;
}
public function getName(){
return $this->name;
}
public function getEmail(){
return $this->email;
}
}
//3. COURSE CLASS (Course.php)
// Stores course details
class Course {
private $courseCode;
private $courseName;
private $credit;
// Constructor
public function __construct($courseCode, $courseName, $credit){
$this->courseCode = $courseCode;
$this->courseName = $courseName;
$this->credit = $credit;
}
// Getter methods
public function getCourseCode(){
return $this->courseCode;
}
public function getCourseName(){
return $this->courseName;
}
public function getCredit(){
return $this->credit;
}
}
// FUNCTION TO REGISTER STUDENT FOR A COURSE
// Stores registration into database
function registerCourse($pdo, $regNumber, $courseCode){
// SQL query to insert registration
$sql = "INSERT INTO registrations (reg_number, course_code)
VALUES (:regNumber, :courseCode)";
// Prepare statement
$stmt = $pdo->prepare($sql);
// Bind parameters
$stmt->bindParam(":regNumber", $regNumber);
$stmt->bindParam(":courseCode", $courseCode);
// Execute query
if($stmt->execute()){
echo "Course registration successful.<br>";
}else{
echo "Registration failed.<br>";
}
}
// FUNCTION TO DISPLAY COURSES REGISTERED BY A STUDENT
function getStudentCourses($pdo, $regNumber){
// SQL query using JOIN
$sql = "SELECT courses.course_code, courses.course_name, courses.credit
FROM courses
JOIN registrations
ON courses.course_code = registrations.course_code
WHERE registrations.reg_number = :regNumber";
// Prepare query
$stmt = $pdo->prepare($sql);
// Bind parameter
$stmt->bindParam(":regNumber", $regNumber);
// Execute query
$stmt->execute();
// Fetch all results
$courses = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Display courses in table format
echo "<h3>Courses Registered by Student</h3>";
echo "<table border='1'>";
echo "<tr>
<th>Course Code</th>
<th>Course Name</th>
<th>Credit</th>
</tr>";
foreach($courses as $row){
echo "<tr>";
echo "<td>".$row['course_code']."</td>";
echo "<td>".$row['course_name']."</td>";
echo "<td>".$row['credit']."</td>";
echo "</tr>";
}
echo "</table>";
}
// MAIN PROGRAM EXECUTION (index.php)
// Create Database object
$db = new Database();
// Get PDO connection
$pdo = $db->getConnection();
// Create Student object
$student = new Student("T23-18926", "Amos Daniel", "amos@email.com");
// Create Course object
$course = new Course("CS101", "Introduction to Programming", 3);
// Register student for course
registerCourse($pdo, $student->getRegNumber(), $course->getCourseCode());
// Retrieve and display courses registered by the student
getStudentCourses($pdo, $student->getRegNumber());
?>Question Two
A university plans to develop a course registration system to manage students and courses.
Each student has a registration number, name, and email address, while each course has a course code, course name, and credit value. A student may register for multiple courses. In a previous question, you designed classes and database interaction logic for this system.
Using the same system requirements and data structure described above, write PHP code that implements a RESTful web service to manage student course registration. Your web service must provide API endpoints that allow clients to register a student for a course, retrieve all courses registered by a specific student, retrieve all students, retrieve all courses, and remove a course registration for a student. Each endpoint must use the appropriate HTTP method, return responses in JSON format, send suitable HTTP status codes, and follow REST principles.
Use the same entities and attributes specified in the scenario (students and courses) when designing your endpoints and logic. Provide only the PHP code required to implement this REST web service. Do not include explanations or database creation scripts.
(30 Marks)
// RESTFUL WEB SERVICE FOR UNIVERSITY COURSE REGISTRATION
// Returns JSON responses and follows REST principles
<?php
//i. Set response type to JSON
header("Content-Type: application/json");
//ii. DATABASE CONNECTION USING PDO
try{
// Connect to database
$pdo = new PDO(
"mysql:host=localhost;dbname=university_db",
"root",
""
);
// Enable PDO error handling
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
// Return error if connection fails
http_response_code(500);
echo json_encode(["error"=>"Database connection failed"]);
exit;
}
//iii. DETERMINE HTTP METHOD AND REQUEST PATH
// Get request method (GET, POST, DELETE)
$method = $_SERVER['REQUEST_METHOD'];
// Get requested URI
$request = $_SERVER['REQUEST_URI'];
// Break URI into parts
$path = explode("/", trim($request,"/"));
// iv. ENDPOINT 1: GET /students
// Retrieve all students
if($method == "GET" && $path[0] == "students"){
$sql = "SELECT reg_number,name,email FROM students";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$students = $stmt->fetchAll(PDO::FETCH_ASSOC);
http_response_code(200);
// Return students as JSON
echo json_encode($students);
}
// v. ENDPOINT 2: GET /courses
// Retrieve all courses
elseif($method == "GET" && $path[0] == "courses"){
$sql = "SELECT course_code,course_name,credit FROM courses";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$courses = $stmt->fetchAll(PDO::FETCH_ASSOC);
http_response_code(200);
echo json_encode($courses);
}
// vi. ENDPOINT 3: GET /students/{regNumber}/courses
// Retrieve courses registered by a specific student
elseif($method == "GET" && $path[0] == "students" && isset($path[2]) && $path[2] == "courses"){
$regNumber = $path[1];
$sql = "SELECT courses.course_code, courses.course_name, courses.credit
FROM courses
JOIN registrations
ON courses.course_code = registrations.course_code
WHERE registrations.reg_number = :reg";
$stmt = $pdo->prepare($sql);
// Bind student registration number
$stmt->bindParam(":reg",$regNumber);
$stmt->execute();
$courses = $stmt->fetchAll(PDO::FETCH_ASSOC);
http_response_code(200);
echo json_encode($courses);
}
//vii. ENDPOINT 4: POST /register
// Register a student for a course
elseif($method == "POST" && $path[0] == "register"){
// Get JSON input data
$data = json_decode(file_get_contents("php://input"),true);
$regNumber = $data["reg_number"];
$courseCode = $data["course_code"];
$sql = "INSERT INTO registrations (reg_number,course_code)
VALUES (:reg,:course)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(":reg",$regNumber);
$stmt->bindParam(":course",$courseCode);
if($stmt->execute()){
http_response_code(201);
echo json_encode(["message"=>"Student registered for course"]);
}else{
http_response_code(400);
echo json_encode(["error"=>"Registration failed"]);
}
}
// viii. ENDPOINT 5: DELETE /register/{regNumber}/{courseCode}
// Remove a course registration
elseif($method == "DELETE" && $path[0] == "register"){
$regNumber = $path[1];
$courseCode = $path[2];
$sql = "DELETE FROM registrations
WHERE reg_number = :reg
AND course_code = :course";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(":reg",$regNumber);
$stmt->bindParam(":course",$courseCode);
if($stmt->execute()){
http_response_code(200);
echo json_encode(["message"=>"Course registration removed"]);
}else{
http_response_code(400);
echo json_encode(["error"=>"Deletion failed"]);
}
}
//ix. HANDLE INVALID ENDPOINT
else{
http_response_code(404);
echo json_encode(["error"=>"Endpoint not found"]);
}
?>