function manageSubjects($config, $parameters) { if (!isset($_SESSION['uname']) || isset($_SESSION['urole']) && 3 != $_SESSION['urole']) { header('Location: /'); exit; } $userName = $_SESSION['uname']; loadModel('models/Students'); $profile = getStudentByStudentUserName($config, $userName); if (!$profile['status']) { return ['status' => false, 'message' => 'Invalid student profile found.']; } $student = $profile['student']; loadModel('models/Subjects'); $remainingSubjects = getSubjectsNotTakenByStudent($config, $student['ID']); if (!$remainingSubjects['status']) { return ['status' => false, 'message' => 'An error occured while trying to get remaining subjects.']; } if ('POST' == getRequestMethod()) { if (!isset($_SESSION['uname'])) { header('Location: /students'); } $studentName = $_SESSION['uname']; $result = addSubjectsToStudent($config, array_merge(['UserName' => $studentName], $_POST)); $_SESSION['addStatus'] = $result['status']; $_SESSION['addStatusMessage'] = $result['message']; header('Location: /students'); } return $remainingSubjects; }
function addSubjectsToStudent($config, $post) { $student = getStudentByStudentUserName($config, $post['UserName']); if (!$student['status']) { return $student; } $connection = getConnection($config); if (false === $connection['status']) { return $connection; } $connection = $connection['connection']; try { if (isset($post['Subjects']) && !empty($post['Subjects']) && is_array($post['Subjects'])) { foreach ($post['Subjects'] as $subjectItem) { $query = sprintf(' INSERT INTO `StudentsSubjectsMatch` ( `UserID`, `SubjectID` ) VALUES ( :UserID, :SubjectID ) '); $preparedStatement = $connection->prepare($query); $preparedStatement->bindValue(':UserID', $student['student']['ID'], PDO::PARAM_INT); $preparedStatement->bindValue(':SubjectID', $subjectItem, PDO::PARAM_INT); $result = $preparedStatement->execute(); } } closeConnection($connection); return ['status' => true, 'message' => 'Subjects successfully added to Student.']; } catch (Exception $e) { closeConnection($connection); return ['status' => false, 'message' => $e->getMessage(), 'code' => 500]; } }