Reputation: 2007
I have a simple mysql select query in my PHP code:
$result = mysql_query("SELECT text FROM example ORDER BY rank DESC");
while($row = mysql_fetch_array($result))
{
echo $row['text'] . "<br>";
}
and this MySql table:
text | rank
--------+--------
google | 245
--------+--------
yahoo | 32
--------+--------
bing | 12
When I get the results from the query, something like this gets displayed:
yahoo
google
bing
I want Google to be in front. I guess Yahoo is in first because it starts with "3".
How could I make the query order the results by the size of the numbers in rank?
Thanks...
Upvotes: 4
Views: 19294
Reputation: 531
$result = mysql_query("SELECT * FROM `example` ORDER BY `rank` DESC");
while($row = mysql_fetch_array($result))
{
echo $row['text'] ."<br>";
}
Upvotes: 1
Reputation: 28000
The correct solution, of course, is to use the correct data type. As a workaround you could cast the data to number on the fly:
SELECT text FROM example ORDER BY rank + 0 DESC
or:
SELECT text FROM example ORDER BY cast(rank as unsigned) DESC
Upvotes: 7
Reputation: 26167
I'm guessing the rank
field is some kind of string type. Make it a numeric type int
and it will order properly
Upvotes: 9
Reputation: 26765
What's the data type of rank
in your SQL schema? Set it to a numeric type.
Upvotes: 3
Reputation: 146310
Try this:
$result = mysql_query("SELECT * FROM example ORDER BY rank DESC");
while($row = mysql_fetch_array($result))
{
echo $row['text'] . " ". $row['rank'] ."<br>";
}
And see if the ranks are being sorted correctly.
Upvotes: 1