You must use the field names (or columns) in the query. So, this query is OK.
$query = "SELECT pid, lastname, games, totpoints, (totpoints / games) AS pointspg FROM roster";
because it will now cause a calculated field to be returned in the results array. But, the calculated field cannot be used in an ORDER BY clause as in:
$query = "SELECT pid, lastname, games, totpoints, (totpoints / games) AS pointspg FROM roster ORDER BY pointspg";
Instead, the entire calculation must be repeated again in the ORDER BY clause as in:
$query = "SELECT pid, lastname, games, totpoints, (totpoints / games) AS pointspg FROM roster ORDER BY (totpoints / games) ";
So, the calculation is done twice in the SELECT statement... not too efficient in my book... and when the calculations start to get hairy, it just seems like a messy way to do it to me.
So, I move the results to an array, make the computations I want, then sort the array into the desired order.
$query = "SELECT pid, lastname, games FROM roster";
// load results to array
while ($row = @ mysql_fetch_array($result))
{
$myarray[] = $row;
}
// perform average points calculation
$arrcnt = count($myarray);
for ($i = 0; $i < $arrcnt ;$i++)
{
$pointspg = $myarray[$i]["totpoints"] / $myarray[$i]["totgames"];
$myarray[$i]["pointspg"] = $pointspg;
}
// sort the query by the distance
$myarray2 = array_csort($myarray,"pointspg");
// now do whatever with the sorted array
// the array sort looks like this
function array_csort($marray, $column)
{
foreach ($marray as $row)
{
$sortarr[] = $row[$column];
}
array_multisort($sortarr, SORT_NUMERIC, SORT_ASC, $marray);
return $marray;
}
By the way, I notice that the original query has a LIMIT 0,1 clause in it which guarantees only the first record will be returned. ????