Jump to content

How can I generate Class Position?


Olumide
Go to solution Solved by Barand,

Recommended Posts

I am a novice and working on a result project project for elementary school. There should a position such as 1st, 2nd, 3rd,... till the last person in the class with the lowest mark. I could not use the php ordinal suffix to this. I need your help to help me rectify this issue below and attached is the picture of the current output but instead of the only numbers, I something like the red painted numbers.

 

$semester = $_GET['semester'] ?? '';
$class =    $_GET['class'] ?? '';
$midend = $_GET['midend'] ?? 'M';

$res = $pdo->prepare("SELECT sessionid
                        FROM semester
                        WHERE id = ?
                        ");
$res->execute([$semester]);
$session = $res->fetchColumn();

switch ($midend) {
    case 'M': $res = $pdo->prepare("SELECT subjectname
                                         , stname
                                         , score
                                         , @seq := IF(subjectname = @prevs, @seq+1, 1) as seq
                                         , @rank := IF(score = @prev, @rank, @seq) as rank
                                         , @prev := score as prev
                                         , @prevs := subjectname as prevs
                                    FROM (
                                            SELECT cl.classname
                                                 , sb.subjectname
                                                 , concat(st.firstname, ' ', st.lastname) as stname
                                                 , round( sum( case exam when 'Exam' then score/70*100
                                                                         else score*10
                                                                         end 
                                                              ) / COUNT(distinct exam) ) as score
                                            FROM student_class stc 
                                                 JOIN student st ON stc.studentid = st.id
                                                 JOIN class cl ON stc.classid = cl.id
                                                 JOIN level l ON cl.levelid = l.id
                                                 JOIN course c ON l.id = c.levelid
                                                 JOIN subject sb ON c.subjectid = sb.id
                                                 JOIN result r ON r.courseid = c.id AND r.studentclassid = stc.id
                                            WHERE stc.semesterid = ?
                                                    AND exam = 'CA1'
                                                    AND cl.id = ?
                                            GROUP BY c.id, sb.id, st.id
                                            ORDER BY subjectname, score DESC
                                            LIMIT 9223372036854775807        -- MariaDB bug workaround
                                         ) ordered
                                         JOIN (SELECT @prevs:='', @prev:=0, @seq:=0, @rank:=0) init
                                    ");
              $res->execute([ $semester, $class ]);
              $chkm = 'checked';
              $chke = $chky = '';
              break;
    case 'E':  $res = $pdo->prepare("SELECT subjectname
                                         , stname
                                         , score
                                         , @seq := IF(subjectname = @prevs, @seq+1, 1) as seq
                                         , @rank := IF(score = @prev, @rank, @seq) as rank
                                         , @prev := score as prev
                                         , @prevs := subjectname as prevs
                                    FROM (
                                            SELECT   sb.subjectname
                                                 , concat(st.firstname, ' ', st.lastname) as stname
                                                 , round( sum( score )) as score
                                            FROM student_class stc 
                                                 JOIN student st ON stc.studentid = st.id
                                                 JOIN class cl ON stc.classid = cl.id
                                                 JOIN level l ON cl.levelid = l.id
                                                 JOIN course c ON l.id = c.levelid
                                                 JOIN subject sb ON c.subjectid = sb.id
                                                 JOIN result r ON r.courseid = c.id AND r.studentclassid = stc.id
                                            WHERE stc.semesterid = ?
                                                    AND cl.id = ?
                                            GROUP BY c.id, sb.id, st.id
                                            ORDER BY subjectname, score DESC
                                            LIMIT 9223372036854775807        -- MariaDB bug workaround
                                         ) ordered 
                                         JOIN (SELECT @prevs:='', @prev:=0, @seq:=0, @rank:=0) init
                                    ");
              $res->execute([ $semester, $class ]);
              $chke = 'checked';
              $chkm = $chky = '';
              break;       
    default:  $res = $pdo->prepare("SELECT subjectname
                                         , stname
                                         , score
                                         , @seq := IF(subjectname = @prevs, @seq+1, 1) as seq
                                         , @rank := IF(score = @prev, @rank, @seq) as rank
                                         , @prev := score as prev
                                         , @prevs := subjectname as prevs
                                    FROM (
                                            SELECT   sb.subjectname
                                                 , concat(st.firstname, ' ', st.lastname) as stname
                                                 , round( sum( score )/count(distinct sm.id)) as score
                                            FROM student_class stc 
                                                 JOIN student st ON stc.studentid = st.id
                                                 JOIN class cl ON stc.classid = cl.id
                                                 JOIN level l ON cl.levelid = l.id
                                                 JOIN course c ON l.id = c.levelid
                                                 JOIN subject sb ON c.subjectid = sb.id
                                                 JOIN result r ON r.courseid = c.id AND r.studentclassid = stc.id
                                                 JOIN semester sm ON stc.semesterid = sm.id
                                                 JOIN session sn ON sm.sessionid = sn.id
                                            WHERE sm.sessionid = ?
                                                    AND cl.id = ?
                                            GROUP BY cl.id, sb.id, st.id
                                            ORDER BY subjectname, score DESC
                                            LIMIT 9223372036854775807        -- MariaDB bug workaround
                                         ) ordered 
                                         JOIN (SELECT @prevs:='', @prev:=0, @seq:=0, @rank:=0) init
                                    ORDER BY subjectname, score DESC     
                                    ");
              $res->execute([ $session, $class ]);
              $chky = 'checked';
              $chkm = $chke = '';
              break;       
}
function getOrdinalSuffix($score) {
    $score = abs($score) % 100;
    $lastChar = substr($score, -1, 1);
    switch ($lastChar) {
        case '1' : return ($score == '11') ? 'th' : 'st';
        case '2' : return ($score == '12') ? 'th' : 'nd';
        case '3' : return ($score == '13') ? 'th' : 'rd'; 
    }
    return 'th';  
}
$list = ''; 
for ($score = 1; $score < 150; $score++) { 
    $list .= "$score" . getOrdinalSuffix($score) . "\n"; 
}
///print "$list";

$data = [];
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'] ];
}


function clsOpts($db, $current='')
{
    $opts = "<option value=''>- select class -</option>\n";
    $res = $db->query("SELECT id
                             , classname
                        FROM class
                        ORDER BY substring(classname, 6, 2)+0     
                       ");
    foreach ($res as $r) {
        $sel = $r['id'] == $current ? 'selected' : '';
        $opts .= "<option $sel value='{$r['id']}'>{$r['classname']}</option>\n";
    }
    return $opts;
}

function nameBar($name, $val)
{
    $wid = 400;
    $ht = 32;
    $bar = "<svg width='90%' viewBox='0 0 $wid $ht'>\n
            <defs>
            <linearGradient id='pchi' x1='0' y1='0' x2='0' y2='1'>
                <stop offset='0%' stop-color='#54BC54'/>
                <stop offset='10%' stop-color='#54BC54'/>
                <stop offset='15%' stop-color='#eee'/>
                <stop offset='20%' stop-color='#54BC54'/>
                <stop offset='100%' stop-color='#0B7604'/>
                </lineargradient>
            <linearGradient id='pclo' x1='0' y1='0' x2='0' y2='1'>
                <stop offset='0%' stop-color='#E02222'/>
                <stop offset='10%' stop-color='#E02222'/>
                <stop offset='15%' stop-color='#eee'/>
                <stop offset='20%' stop-color='#E02222'/>
                <stop offset='100%' stop-color='#A91723'/>  
                </lineargradient>
            <linearGradient id='pcmid' x1='0' y1='0' x2='0' y2='1'>
                <stop offset='0%' stop-color='#F2D335'/>
                <stop offset='10%' stop-color='#F2D335'/>
                <stop offset='15%' stop-color='#eee'/>
                <stop offset='20%' stop-color='#F2D335'/>
                <stop offset='100%' stop-color='#EC9807'/>
                </lineargradient>
            <style type='text/css'>
                rect { opacity: 0.2; }
            </style>
            </defs>
            ";
    $max = 100;
    $pix = $wid/$max;
    if ($val > $max) $val = $max;
    // percentage labels
//    for ($p=25; $p<=75; $p+=25) {
//        $ty=8;
//        $tx = $p * $pix;
//        $bar .= "<path d='M $tx $ty l 0 4' stroke='#AAA' />
//            <text x='$tx' y='$ty' class='pcent' >{$p}%</text>\n";
//    }
    // draw bar
    $w = $val * $pix;
    $h = $ht-12;
    
//    if ($val >= 80) $barfill = 'url(#pchi)';
//    elseif ($val >= 50) $barfill = 'url(#pcmid)';
//    else $barfill = 'url(#pclo)';
    $barfill = 'url(#pchi)';
//    $bar .= "<rect x='0' y='12' width='$wid' height='$h' stroke='#444' fill='#DDD' />\n";
    $bar .= "<rect x='0' y='12' width='$w' height='$h' fill='$barfill' />\n";
    $ty = $ht-4;
    $bar .= "<text x='4' y='$ty' fill='#000'>$name</text>\n";
    $bar .= "</svg>\n";
    return $bar;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Student Top Results</title>
<link rel="stylesheet" href="assets/css/w3.css">
<!--<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> -->
<script src="assets/js/jquery.js"></script>
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> 
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script type='text/javascript'>
    $().ready(function() {
        
    })
</script>
<style type='text/css'>
table {
    width: 94%;
    margin: 0 auto;
    }

</style>
</head>
<body>
    <header class='w3-container w3-padding w3-margin'>
        <h1><img src='logo1.png' height='65' alt='logo'>Student Top Results</h1>
    </header>
    <div class='w3-bar w3-light-gray'>
    <form id='form1'>
        <label class='w3-bar-item' for='search'>Class </label>
        <select class='w3-input w3-bar-item w3-border ' name='class' id='class' > 
            <?= clsOpts($pdo, $class) ?>
        </select>
        <label class='w3-bar-item' for='search'>Term </label>
        <select class='w3-input w3-bar-item w3-border ' name='semester' id='semester' > 
            <?= semesterOptions($pdo, 0, $semester) ?>
        </select>
        <span class='w3-bar-item'>
            &emsp;<input type='radio' name='midend' value = 'M' <?=$chkm?>> Mid-term
            &emsp;<input type='radio' name='midend' value = 'E' <?=$chke?>> End-term
            &emsp;<input type='radio' name='midend' value = 'Y' <?=$chky?>> End-year
        </span>
        &emsp;<button class='w3-button w3-bar-item w3-blue-gray w3-margin-left'>Show lists</button>
        
    </form>
    </div>
    <div class='w3-container w3-margin-top'>
    <?php
    if ($data) {
        echo "<div class='w3-row'>";
        foreach ($data as $subname => $subdata) {
            
            $studs = array_pad($subdata['students'], 3, ['name'=>'&nbsp;', 'score'=>'&nbsp;']);
                     
            echo "<div class='w3-col w3-card s12 m4 w3-margin-top'>
                 <div class='w3-panel w3-margin w3-padding w3-large w3-center w3-blue-gray'>$subname</div>
                 <table>";
            
//            for ($i=0; $i<3; $i++) {
//                $stud = $studs[$i];
//                echo "
//                     <tr><td><i class='fa fa-trophy' style='color: {$awards[$i]};'></i>&ensp;
//                          {$stud['name']}</td>
//                          <td>{$stud['score']}</td>
//                     </tr>
//                ";
//            } 

            foreach ($subdata['students'] as $k => $stud) {
                if (isset($awards[$stud['rank']])) {
                    $trophy = "<i class='fa fa-trophy' style='color: {$awards[$stud['rank']]};'></i>";
                }
                else $trophy = '&emsp;';
                    echo "
                         <tr>
                            <td>{$stud['rank']}</td>
                            <td>$trophy&ensp; " .
                                nameBar($stud['name'], $stud['score']) .
                              "</td><td>{$stud['score']}</td>
                         </tr>\n
                    ";
            }

            echo "</table>\n</div>";
        }
        
    }
    ?>

 

Untitled.png

Link to comment
Share on other sites

try this function

<?php
  /********************************************
  * Derive ordinal suffix for $n
  * 
  * @param int $n     the number
  * @returns string   number with suffix eg 23rd   
  */
  function ordinal($n) 
  {
      $str = "$n";
      $t = $n > 9 ? substr($str,-2,1) : 0;
      $u = substr($str,-1);
      if ($t==1) 
        return $str . 'th';
      else 
          switch ($u) 
          {
              case 1: return $str . 'st';
              case 2: return $str . 'nd';
              case 3: return $str . 'rd';
              default: return $str . 'th';
          }
  }
?>

examples...

  echo ordinal(1).'<br>';      // 1st
  echo ordinal(11).'<br>';     // 11th
  echo ordinal(101).'<br>';    // 101st
  echo ordinal(2).'<br>';      // 2nd
  echo ordinal(3).'<br>';      // 3rd
  echo ordinal(8).'<br>';      // 8th

 

Link to comment
Share on other sites

36 minutes ago, Barand said:

You are indeed a guru sir/ Please how do I include the function in the code? I tried something like this but not getting the result.

 

function ordinal($n) 
  {
      $str = "$n";
      $t = $n > 9 ? substr($str,-2,1) : 0;
      $u = substr($str,-1);
      if ($t==1) 
        return $str . 'th';
      else 
          switch ($u) 
          {
              case 1: return $str . 'st';
              case 2: return $str . 'nd';
              case 3: return $str . 'rd';
              default: return $str . 'th';
          }
  }

$data = [];
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'] ];
}

 

Link to comment
Share on other sites

13 minutes ago, Barand said:

try

foreach ($res as $r) {
    if (!isset($data[$r['subjectname']])) {
        $data[$r['subjectname']]['students'] = [];
    }
    
    $position = ordinal($r['rank']);
    $data[$r['subjectname']]['students'][] = [ 'name' => $r['stname'], 'score' => $r['score'], 'rank' => $position ];
}

 

Thanks so much sir. I got error on line 169: $position = ordinal($r['rank']);

Fatal error: Uncaught Error: Call to undefined function ordinal() in C:\xampp\htdocs\local\position.php:169 Stack trace: #0 {main} thrown in  C:\xampp\htdocs\local\position.php on line 169

Link to comment
Share on other sites

1 hour ago, Barand said:

Have you removed that function definition that was in the first post? Why?

Thanks for the solution sir. But, when I populated the database with data to have many data. Attached is the position output. From the screenshort, 80 should be 3rd, while 76 should 4th till the lowest. What is likely the problem with it sir?

position.png

Link to comment
Share on other sites

11 minutes ago, Barand said:

No problem. For example, the one with a score of 76 has five pupils with a higher score and is, therefore, sixth in the class.

Thanks so much sir. I appreciate you dearly. But, please sir, I want to integrate the function again in another script, I copied the sql querry and paste it in the term selection. It is not working because I got it wrong, but it is settled in the other part. But, I want to have it in the checking result part so that each student checking his or her result can know his score unlike the formal one that will show all the students which is for the admin.

Thanks so much sir.

 

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>-->";
                                  $res = $pdo->prepare("SELECT subjectname
                                         , stname
                                         , score
                                         , @seq := IF(subjectname = @prevs, @seq+1, 1) as seq
                                         , @rank := IF(score = @prev, @rank, @seq) as rank
                                         , @prev := score as prev
                                         , @prevs := subjectname as prevs
                                    FROM (
                                            SELECT cl.classname
                                                 , sb.subjectname
                                                 , concat(st.firstname, ' ', st.lastname) as stname
                                                 , round( sum( case exam when 'Exam' then score/70*100
                                                                         else score*10
                                                                         end 
                                                              ) / COUNT(distinct exam) ) as score
                                            FROM student_class stc 
                                                 JOIN student st ON stc.studentid = st.id
                                                 JOIN class cl ON stc.classid = cl.id
                                                 JOIN level l ON cl.levelid = l.id
                                                 JOIN course c ON l.id = c.levelid
                                                 JOIN subject sb ON c.subjectid = sb.id
                                                 JOIN result r ON r.courseid = c.id AND r.studentclassid = stc.id
                                            WHERE stc.semesterid = ?
                                                    AND exam = 'CA1'
                                                    AND cl.id = ?
                                            GROUP BY c.id, sb.id, st.id
                                            ORDER BY subjectname, score DESC
                                            LIMIT 9223372036854775807        -- MariaDB bug workaround
                                         ) ordered
                                         JOIN (SELECT @prevs:='', @prev:=0, @seq:=0, @rank:=0) init
                                    ");
              $res->execute([ $semester, $class ]);
             # $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>";
                                  $res = $pdo->prepare("SELECT subjectname
                                         , stname
                                         , score
                                         , @seq := IF(subjectname = @prevs, @seq+1, 1) as seq
                                         , @rank := IF(score = @prev, @rank, @seq) as rank
                                         , @prev := score as prev
                                         , @prevs := subjectname as prevs
                                    FROM (
                                            SELECT   sb.subjectname
                                                 , concat(st.firstname, ' ', st.lastname) as stname
                                                 , round( sum( score )) as score
                                            FROM student_class stc 
                                                 JOIN student st ON stc.studentid = st.id
                                                 JOIN class cl ON stc.classid = cl.id
                                                 JOIN level l ON cl.levelid = l.id
                                                 JOIN course c ON l.id = c.levelid
                                                 JOIN subject sb ON c.subjectid = sb.id
                                                 JOIN result r ON r.courseid = c.id AND r.studentclassid = stc.id
                                            WHERE stc.semesterid = ?
                                                    AND cl.id = ?
                                            GROUP BY c.id, sb.id, st.id
                                            ORDER BY subjectname, score DESC
                                            LIMIT 9223372036854775807        -- MariaDB bug workaround
                                         ) ordered 
                                         JOIN (SELECT @prevs:='', @prev:=0, @seq:=0, @rank:=0) init
                                    ");
              $res->execute([ $semester, $class ]);
              #$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>";
                                  $res = $pdo->prepare("SELECT subjectname
                                         , stname
                                         , score
                                         , @seq := IF(subjectname = @prevs, @seq+1, 1) as seq
                                         , @rank := IF(score = @prev, @rank, @seq) as rank
                                         , @prev := score as prev
                                         , @prevs := subjectname as prevs
                                    FROM (
                                            SELECT   sb.subjectname
                                                 , concat(st.firstname, ' ', st.lastname) as stname
                                                 , round( sum( score )/count(distinct sm.id)) as score
                                            FROM student_class stc 
                                                 JOIN student st ON stc.studentid = st.id
                                                 JOIN class cl ON stc.classid = cl.id
                                                 JOIN level l ON cl.levelid = l.id
                                                 JOIN course c ON l.id = c.levelid
                                                 JOIN subject sb ON c.subjectid = sb.id
                                                 JOIN result r ON r.courseid = c.id AND r.studentclassid = stc.id
                                                 JOIN semester sm ON stc.semesterid = sm.id
                                                 JOIN session sn ON sm.sessionid = sn.id
                                            WHERE sm.sessionid = ?
                                                    AND cl.id = ?
                                            GROUP BY cl.id, sb.id, st.id
                                            ORDER BY subjectname, score DESC
                                            LIMIT 9223372036854775807        -- MariaDB bug workaround
                                         ) ordered 
                                         JOIN (SELECT @prevs:='', @prev:=0, @seq:=0, @rank:=0) init
                                    ORDER BY subjectname, score DESC     
                                    ");
              $res->execute([ $session, $class ]);
    }
    
    $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,
                                             'rank' => 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###############
        /***** manipulating here **************
         * 
         * 
         * 
         * /
         * */

        /********************************************
  * Derive ordinal suffix for $n
  * 
  * @param int $n     the number
  * @returns string   number with suffix eg 23rd   
  */
  function ordinal($n) 
  {
      $str = "$n";
      $t = $n > 9 ? substr($str,-2,1) : 0;
      $u = substr($str,-1);
      if ($t==1) 
        return $str . 'th';
      else 
          switch ($u) 
          {
              case 1: return $str . 'st';
              case 2: return $str . 'nd';
              case 3: return $str . 'rd';
              default: return $str . 'th';
          }
  }

  //function end
//$data = [];
  foreach ($res as $r) {
    if (!isset($data[$r['subjectname']])) {
        $data[$r['subjectname']]['students'] = [];
    }
    
    $position = ordinal($r['rank']);
    $data[$r['subjectname']]['students'][] = [ 'name' => $r['stname'], 'score' => $r['score'], 'rank' => $position ];
}


    /*    //hffffffffff
        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 = "<tr><td colspan='13'>No results found</td></tr>\n";
    }

    ################################################################################
    #  Get list of gradings                                                        #
    ################################################################################
    $res = $pdo->query("SELECT GROUP_CONCAT( grade, concat('&nbsp;(',comments,')'), '&nbsp;', concat(lomark,'&nbsp;-&nbsp;',himark)
                               ORDER BY id SEPARATOR ', ')
                        FROM examgrade
                        #WHERE level_group = ($level > 5)
                         WHERE level_group = ($level > 6)
                        ");
    $grade_list = $res->fetchColumn();

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

    $res = $pdo->query('SELECT MIN(date_format(date_from, "%W %M %e, %Y")) as next_term

        FROM semester

            WHERE date_from > CURDATE()');
    $nextterm = $res->fetchColumn();
    #################################

################################################################################
#  Get end of term assessments                                                 #
################################################################################
$res = $pdo->prepare("SELECT    a.type
                              , a.assessname
                              , e.grade
                        FROM student_class stc
                               JOIN eot_assessment e ON e.studentclassid = stc.id
                               JOIN assessment a ON e.assessmentid = a.id 
                               #JOIN semester sm ON sm.id = stc.date_untilid 
                               JOIN semester sm ON sm.id = stc.semesterid
                        WHERE stc.studentid = ? 
                            AND sm.id = ? 
                        ");
$res->execute( [ $student, $semester ] );
$ass_data = $res->fetchAll(PDO::FETCH_GROUP);
$afflist = $psychlist = '';

if ($ass_data) {
    
    $afflist = "<table class='w3-table assess-tbl' >
                <tr><th>Domain</th><th>Grade</th></tr>\n";
    foreach ($ass_data['Affective'] as $agrades) {
        $afflist .= "<tr><td>{$agrades['assessname']}</td><td>{$agrades['grade']}</td></tr>\n";
    }
    $afflist .= "</table>\n";
    
    $psychlist = "<table class='w3-table assess-tbl' >
                  <tr><th>Domain</th><th>Grade</th></tr>\n";
    foreach ($ass_data['Psychomotor'] as $pgrades) {
        $psychlist .= "<tr><td>{$pgrades['assessname']}</td><td>{$pgrades['grade']}</td></tr>\n";
    }
    $psychlist .= "</table>\n";
}

 

sample3.png

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.