Jump to content

Getting a users rank from a mysql table with PDO


mediabob

Recommended Posts

Hi, I am trying to get the rank of a user in a database, based on his score, so when the user logs in he can see his rank. I am using this to build a list of all users ordered by their score for a different section.

$stmt = $dbh->query("SELECT * FROM $table ORDER BY score DESC"); 
 
    $rank = 0;
        while($uid = $stmt->fetchObject()) {
          $rank++;
          echo $uid->uname ."is ranked". $rank;
        };

How can I get ONLY a users rank in the db based on his ID number, if I have a table like, .

 

| user | ID | score |

Jim  | 2568 | 80

Pete | 5693 | 115

Sam | 3258 | 569

George | 7412 | 30

 

the ID numbers are a unique key

 

If Jim logs in today he will see:

 

Your Current Rank is 3

 

I am using PHP with PDO on a MySQL table. Thanks!

Edited by mediabob
Link to comment
Share on other sites

Get the user's current score and count how many people have a score above that.

 

So using your idea, I have done this, and it works exactly for what I want, is this the best recommended way?

 

 

$stmt = $dbh->query("SELECT COUNT(uid) AS `rank` FROM $table WHERE score > ( SELECT score from $table WHERE uid = $uid )");
$result = $stmt->fetchColumn();
 
echo $result+1;
 
Link to comment
Share on other sites

Or....try to use ALL SQL operator instead to add +1 and everytime to assign new $uid.

 

No....it's the same, b/s we have single output.

SELECT COUNT(*) AS `rank` FROM $table WHERE $table.score >= ALL ( SELECT $table.score FROM $table WHERE $table.id=$userID)
Edited by jazzman1
Link to comment
Share on other sites

Fred    99
Joe     90
Mary    80
Jane    80
Paul    80
Peter   80
Jazzman 80
Barand  70

Jazzman,

if you use >= then your rank is now 7 instead of 3=

 

 

Yes, master, got it....but what about the user with lowest rank named "Barand" :happy-04:

 

If I run next query, "Barand" is getting rang 8 instead 4.

SELECT COUNT(*)+1 as 'rank'  FROM mydb.users WHERE score > (
SELECT score FROM mydb.users WHERE users.UserID=
Edited by jazzman1
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.