ranking system when values are equal

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
wright0768
Forum Newbie
Posts: 6
Joined: Thu Jun 24, 2010 4:20 pm

ranking system when values are equal

Post 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); ?>


User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: ranking system when values are equal

Post 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'];
}
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
wright0768
Forum Newbie
Posts: 6
Joined: Thu Jun 24, 2010 4:20 pm

Re: ranking system when values are equal

Post 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
wright0768
Forum Newbie
Posts: 6
Joined: Thu Jun 24, 2010 4:20 pm

Re: ranking system when values are equal

Post by wright0768 »

Moving the $count++ to the end of the while loop seems to have fixed the problem.
Post Reply