Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

olumidedvd's avatar

PHP Ordinal Surffixes

I am a novice and working on a PHP project for students online result processing. I want to include class position that will grade each students according to the highest scores per score subjects in the class from 1st, 2nd, 3rd, 4th, to the last person in the class population that score the lowest mark.

################################################################################

NOTE:

The student viewing their reult is expected to be logged in and their

student id store in the $_SESSION variable. At this point, if they are not

loggend in they should be transferred to the login page.

For testing, simulate login by setting the required SESSION variable above

################################################################################

$clid = $_GET['classid'] ?? -1;

if (isset($_SESSION['student_id'])) {
    $student = $_SESSION['student_id'];
    $staff = $_GET['staffid'] ?? 0;
}
elseif (isset($_SESSION['staff_id'])) {
    $staff = $_SESSION['staff_id'];
    $student = $_GET['studentid'] ?? 0;
}
else header("Location: login.php");

################################################################################

Get current session

################################################################################ $semester = $_GET['semesterid'] ?? 0;

$res = $pdo->prepare("SELECT ss.sessionname
                         , ss.id as sessionid
                         , sm.semestername
                         , sm.semestername+0 as termno
                         #, sm.date_until as nextterm   # modified
                         , sm.id as smid
                    FROM session ss
                         JOIN semester sm ON sm.sessionid = ss.id
                    WHERE sm.id = ?     
                    ");
$res->execute([$semester]);
$row = $res->fetch();

// $sessionname = $row['sessionname'] ?? ''; $session = $row['sessionid'] ?? 0; // $semestername = $row['semestername'] ?? ''; $termno = $row['termno'] ?? 0; # $nextterm = $row['nextterm'] ?? 0; # modified

if ($clid == -1) {
    $res = $pdo->prepare("SELECT classid
                          FROM student_class
                          WHERE studentid = ?
                            AND semesterid = ?
                         ");
    $res->execute([$student, $semester]);
    $clid = $res->fetchColumn();
}

switch($termno) {
    case 1: $term_headings = "<th>1st<br>Term<br>100</th>
                              <!--<th>&ensp;&ensp;&ensp;&ensp;&ensp;</th>
                              <th>&ensp;&ensp;&ensp;&ensp;&ensp;</th>-->";
                             
          
          $chkm = 'checked';
          $chke = $chky = '';
                              break;
    case 2: $term_headings = "<th>1st<br>Term<br>&nbsp;</th>
                              <th>2nd<br>Term<br>100</th>
                              <th>&ensp;&ensp;&ensp;&ensp;&ensp;</th>";
                              
          
          $chke = 'checked';
          $chkm = $chky = '';
                              break;
    default: $term_headings = "<th>1st<br>Term<br>&nbsp;</th>
                              <th>2nd<br>Term<br>&nbsp;</th>
                              <th>3rd<br>Term<br>100</th>";
                              
             }

$report_title = $termno == 3 ? "End of Year Results" : "End of Term Results";
################################################################################
#  Get scores and put in array with required output structure                  #
################################################################################
$res = $pdo->prepare("SELECT st.id as stid
                             , concat_ws(' ', st.lastname, st.firstname, st.othername) as stname
                             , st.image
                             , cl.classname
                             , st.dob
                             , st.matricno
                             , sc.classid
                             , l.id as level
                             , sn.sessionname
                             , sm.semestername
                             , sm.date_until 
                             , sm.semestername+0 as term
                             , c.subjectid
                             , s.subjectname
                             , exam
                             , score
                        FROM result r
                             JOIN 
                             (
                             student_class sc 
                             JOIN class cl ON sc.classid = cl.id
                             JOIN level l ON cl.levelid = l.id
                             JOIN course c ON c.levelid = l.id
                             JOIN student st ON sc.studentid = st.id
                             JOIN semester sm ON sc.semesterid = sm.id
                             JOIN session sn ON sm.sessionid = sn.id
                             JOIN subject s ON c.subjectid = s.id
                             ) ON r.studentclassid = sc.id AND r.courseid = c.id
                             
                        WHERE sn.id = ?
                          AND studentid = ?
                          #AND sm.date_until = ?
                          AND sm.semestername+0 <= ?
                          AND cl.id = ?
                        ORDER BY c.levelid, sc.id, c.subjectid, sc.semesterid, exam
                        ");
#############################################################################


#############################################################################
$res->execute( [ $session, $student, $termno, $clid ] );
$data = [];
// get data common to all rows from first row
$r = $res->fetch();
if ($r) {
    $studentname = $r['stname'];
    $studentdob = $r['dob'];
    $studentmatricno = $r['matricno'];
    $studentlevel = $r['classname'];
    $studentsession = $r['sessionname'];
    $studentterm = "- Term $termno";
    $nextterm = $r['date_until'];
    $passport = "images/" . $r['image'];                                                                      ### provide image path here
    $level = $r['level'];
    // then process the rest of the row data in the first and remaining rows
    do {
        if (!isset($data[ $r['subjectid'] ])) {
            $data[ $r['subjectid'] ] = [ 'name' => $r['subjectname'],
                                         #'exams' => ['CA1'=>'', 'CA2'=>'', 'CA3'=>'', 'Exam'=>''],
                                        'exams' => ['CA1'=>'', 'CA2'=>'', 'Exam'=>''],
                                         'scores'  => [ 1=>0, 0, 0 ],
                                         'avg' => 0
                                       ];
        }   
        if ($r['term'] == $termno && isset($data[$r['subjectid'] ]['exams'][ $r['exam']])) {
            $data[ $r['subjectid'] ]['exams'][ $r['exam'] ] = $r['score'];
        }
        $data[ $r['subjectid'] ]['scores'][$r['term']] += $r['score'];
    } while ($r = $res->fetch());
// get the avg scores for the class
    $avgs = classAverageScores($pdo, $clid, $session, $termno);
    foreach ($avgs as $s => $av) {
        if (isset($data[$s]))
            $data[$s]['avg'] = round($av,0);
    } 

    ###########my ranking here###############
    foreach ($res as $r) {
if (!isset($data[$r['subjectname']])) {
    $data[$r['subjectname']]['students'] = [];
}

$data[$r['subjectname']]['students'][] = [ 'name' => $r['stname'], 'score' => $r['score'], 'rank' => $r['rank'] ];

} ################################################################################ # Get pupil count # ################################################################################ $res = $pdo->prepare("SELECT COUNT(DISTINCT stc.studentid) AS pupils FROM student_class stc JOIN semester sm ON sm.id = stc.semesterid JOIN result r ON stc.id = r.studentclassid WHERE sm.id = ? AND stc.classid = ? "); $res->execute([ $semester, $clid ]); $pupil_count = $res->fetchColumn();

################################################################################
#  Loop through the data array to construct the output table rows              #
################################################################################



    $tdata = '';
    $n = 1;
    $grand_total = 0;
    $subject_count = 0;
    foreach ($data as $subid => $subdata) {
        $tdata .= "<tr><td>$n</td><td>{$subdata['name']}</td>";
        foreach ($subdata['exams'] as $s) {
            $tdata .= "<td>" . ($s=='' ? '&ndash;' : $s) . "</td>";
        }
        foreach ($subdata['scores'] as $t => $s) {
            if ($s==0) $s = '';
            $tdata .= "<td>" . ($t <= $termno ? $s : '') . "</td>";
        }
        $temp = array_filter($subdata['scores']);
        $total = $temp ? round(array_sum($temp)/count($temp)) : 0;
        $grand_total += $total;
        if ($total) {
            list($grade, $comment) = getGradeComment($pdo, $total, $level);
            $subject_count++;
        }
        else {
            $grade = '-';
            $comment = '-';
        }
        $clr = GRADE_COLOUR[$grade] ?? '#000';
        $tdata .= "<td>$total</td><td>{$subdata['avg']}</td><td style='color:$clr; font-weight: 600;'>$grade</td><td>$comment</td></tr>\n";
        ++$n;
    }
}
else {
    $studentname = '';
    $studentdob = '';
    $studentmatricno = '';
    $studentlevel = '';
    $studentsession = '';
    $studentsemester = '';
    #$nextterm = '';
    $studentterm = '';
    $passport = '';
    $level = '4';
    $pupil_count = 0;
    $grand_total = 0;
    $subject_count = 1;

// $clid = 0; $tdata = "No results found\n"; }

0 likes
2 replies
olumidedvd's avatar

@vincent15000 I don't know how to add images. My problem is, I cannot output the positions of each student in the class such as 1st, 2nd, 3rd, 4th,...

Please or to participate in this conversation.