Jump to content

[SOLVED] MySQL Query: order by 'whatever', change each into a integer then put in a var ?


MasterACE14

Recommended Posts

Morning Everyone,

 

I was wondering, I know you can run a MySQL query to select everything in a table, by using ORDER BY and then you can do it in ascending or descending order. Now once you have done that query, can you then assign a integer to each of the results, so if I ORDERED every person on my website by their 'intelligence' attribute from the database, and did it in descending order(Bigged to smallest), could I then assign each of them a Integer, so the whoever had the highest 'intelligence' out of everyone, they would be assigned 1, and the second highest would be assigned 2 etc. And then I could UPDATE every users 'rank' column in the database and put these integers into it.

 

If this is possible. How can I do it?

 

Regards ACE

Link to comment
Share on other sites

The question really is why would you need to make an extra field to store this data? You can dynamically get a users rank without the need for a new field. For example, to get the top 5.

 

SELECT user FROM tbl ORDER BY intelligence DESC LIMIT 5

 

to get the third heighest rank...

 

SELECT user FROM tbl ORDER BY intelligence DESC LIMIT 2,1

 

and the lowest rank...

 

SELECT user FROM tbl ORDER BY intelligence ASC LIMIT 1

 

You can do what you want, but you probably dont need to.

Link to comment
Share on other sites

To get all of them, you could do something like this:

 

<?php

$query = "SELECT user FROM tbl ORDER BY intelligence DESC";
$result = mysql_query($query)or die(mysql_error());

$i = 1;

while ($row = mysql_fetch_assoc($result)){
   echo "Rank #$i - {$row['user']}<br>";
   $i++;
}

?>

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.