Lance
Lance

Reputation: 4820

SQL Query not ordering results properly

I'm querying my database to return a set of results from highest to lowest. But, it seems as if the query isn't entirely ordering the results that way. My code is as follows:

$query = mysql_query("SELECT * FROM ".$stats_table." ORDER BY ppg DESC")or die(mysql_error());
$count = mysql_num_rows($query);
$i = 0;

while($row = mysql_fetch_assoc($query)) 
{
$team[$i] = $row['team'];
    $ppg[$i]  = $row['ppg'];

    $i++;
}

for($i=0;$i<$count;$i++)
{
echo "".$ppg[$i]." <br /><br />";
}

When I echo out the ppg column set I get the following:

99.7

98.2

97.8

97.4

97.1

96.9

96.8

96.3

96.2

95.5

94.6

94.5

94.3

93.9

93.2

92.8

92.2

91.5

90.8

90.3

106.0

105.9

104.5

103.6

102.6

101.9

101.5

101.3

100.7

100.1 

It seems that for all of the values less than 100 and over 100 it works. But, how can I make this order work with all values instead of just within those less than and above 100?

Thanks,

Lance

Upvotes: 0

Views: 93

Answers (4)

Emil Hemdal
Emil Hemdal

Reputation: 628

You could let PHP sort it.

$query = mysql_query("SELECT * FROM ".$stats_table)or die(mysql_error());

$i = 0;
while($row = mysql_fetch_assoc($query)) {
    $team[$i] = $row['team'];
    $ppg[$i]  = (int)$row['ppg'];
    $i++;
}
sort($ppg, SORT_NUMERIC);
for($i=0;$i<count($ppg);$i++) {
     echo $ppg[$i]." <br /><br />";
}

Upvotes: 0

neknek mouh
neknek mouh

Reputation: 1802

Change the data type to numeric like double, real, float. Try it.

Upvotes: 1

Moseleyi
Moseleyi

Reputation: 2879

Use ORDER BY ABS(ppg) if you don't want to touch your structure

Upvotes: 0

Evgeniy Chekan
Evgeniy Chekan

Reputation: 2665

Make ppg double, real or anything numeric, not varchar.

Upvotes: 0

Related Questions