Page 1 of 1

ranking system when values are equal

Posted: Thu Jun 24, 2010 4:31 pm
by wright0768
I have a ranking system based on correct answers however, when the values of correct answers are equal for more than one user, I want them to be the same rank. For example:
Rank. Username - Correct
1. Test - 5
1. Test1 - 5
1. Test2 - 5
4. Test3 - 2
5. Test4 - 1


The code below just does +1 rank with every username. Does anyone know what needs to be added to the code below or at least point me in the right direction in order to get results like above?

Code: Select all

<?php require_once("includes/session.php"); ?>
<?php require_once("includes/connection.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php
$rank = 1;
$result = mysql_query("SELECT * FROM game ORDER BY correct DESC", $connection);
		if (!$result) {
			die("Database query failed: " . mysql_error());
		}
while ($row = mysql_fetch_array($result))
{

echo $rank . ". " . $row['username']."-". $row['correct']; 
echo "<br />";
$rank++;
}
?>



<?php mysql_close($connection); ?>



Re: ranking system when values are equal

Posted: Thu Jun 24, 2010 4:57 pm
by AbraCadaver
Just a quick try so it can be optimized, but this might work:

Code: Select all

$correct = $rank = $count = 0;

while ($row = mysql_fetch_array($result)) {
	$count++;
	if($correct !=  $row['correct']) {
		$rank = $count;
	}
	echo $rank . ". " . $row['username']."-". $row['correct'];
	echo "<br />";
	$correct = $row['correct'];
}

Re: ranking system when values are equal

Posted: Thu Jun 24, 2010 5:31 pm
by wright0768
Works perfect except when everyone has a correct score of 0. It lists everyone's rank as 0 instead of 1 but I think i can fix this.
Thanks

Re: ranking system when values are equal

Posted: Thu Jun 24, 2010 5:45 pm
by wright0768
Moving the $count++ to the end of the while loop seems to have fixed the problem.