user3320550 user3320550 - 1 month ago 21
MySQL Question

PHP mysql sort greatest to least

I have a database table with a column labeled

earnings
. There are multiple users in this table who have a different amount of earnings. I want to display the top ten people with the most earnings.

This is the code that I currently have:

$result = mysql_query("SELECT * FROM `users` ORDER BY `earnings` DESC") or die(mysql_error());


How can I make it so that for instance if I write
$result['earnings'][3]
it'll give me the user with the fourth highest earnings. Or if I write
$result['user'][3]
it'll give me the username of the person with the fourth highest earnings?

Answer

I want to display the top ten people with the most earnings

Then add in your query LIMIT 10:

$query = mysql_query("SELECT * FROM `users` ORDER BY `earnings` DESC LIMIT 10") or die (mysql_error());

And also do not forget mysql_* is deprecated and will be removed in the future. Use mysqli_* instead.

If you want to fetch, then use while cycle:

while($result = mysql_fetch_array($query))
{
  echo $result['username']; // write username, etc...
}
Comments