0

hy,

I was doing some school project and i stacked in this thing i hope i will get the right answer the thing is i was trying to rank one class students and it works but if two students scored the same result it won't give them the same rank i want it to give them the same rank and jump the next rank and get in to process again.

<?php $result = mysql_query("SELECT * FROM score ORDER BY AVERAGE");
$rank= 0; while($go = mysql_fetch_array($result)){$miki = ++$rank;
$sql = mysql_query("INSERT INTO rank(student_id,avg,rank) VALUES('$go['student_id']','$go['avg']','$miki')"); } ?>

it works, it rank but if two students make the same average it won't rank them the same.

Miki
  • 157
  • 1
  • 8
  • Yes, you seem to know the problem, so how are you planning to fix it? – Devon Bessemer May 15 '17 at 17:15
  • First thing, don't use the mysqli functions. They are depreciated. Use mysqli or PDO functions. – Sloan Thrasher May 15 '17 at 17:16
  • Second, the _'++$rank'_ won't increment $rank, You need to do that outside the string. It will be seen by mysql as (if $rank is 0) _'++0'_ – Sloan Thrasher May 15 '17 at 17:17
  • You have to use a new variable to keep the current average so you can compare it with the next one. – RST May 15 '17 at 17:20
  • @SloanThrasher: `don't use the mysqli functions. They are depreciated. Use mysqli functions` => What? I guess you meant don't use the mysql_* functions. `Second, the '++$rank' won't increment $rank, You need to do that outside the string. It will be seen by mysql as (if $rank is 0) '++0' ` => thats a plain lie. Sure it does? https://3v4l.org/L73An – Xatenev May 19 '17 at 13:23
  • 1
    Original duplicate of [How to assign rank to students to where they share the highest rank when their scores equal?](https://stackoverflow.com/questions/44804612/how-to-assign-rank-to-students-to-where-they-share-the-highest-rank-when-their-s) – Dennis Jun 28 '17 at 15:59

1 Answers1

0

You want to cache the average from the latest run and it's rank, try this:

<?php $result = mysql_query("SELECT * FROM score ORDER BY AVERAGE");
$rank=0; 
$cache_average=null;
$cache_rank=0;

while($go = mysql_fetch_array($result)) {
    if($go['avg'] != $cache_average)
        $cache_rank = $rank;

    $sql = mysql_query("INSERT INTO rank(student_id,avg,rank) VALUES('$go['student_id']','$go['avg']','$cache_rank')"); 

    $cache_average = $go['avg'];
    $rank++;
} 
?>
Cpt.Kangar00
  • 211
  • 1
  • 7