Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ORDER BY % which is calculated inside original while loop

Tags:

php

mysql

I want to order results based on an maths sum answer within the main results query, heres what I mean:

My current code looks something like this:

$query  = "SELECT * FROM foo WHERE foobar='{$fobo}' ORDER BY id DESC";
$result = mysql_query($query);

 while($row = mysql_fetch_array($result))
 {

   $percent = round((100 * $row['wins'] / ($row['wins'] + $row['loses'])));

     echo 'blah blah blah' . $percent;

}

As you can see I currently ORDER BY id:

$query  = "SELECT * FROM foo WHERE foobar='{$fobo}' ORDER BY id DESC";

but I want to ORDER BY the $percent answer but thats calculated inside the while loop.

I tried creating a query and putting it before the main results query:

$p  = "SELECT wins, loses FROM foo WHERE foobar='{$fobo}'";
$pr = mysql_query($p);

$pow = mysql_fetch_array($pr);
$percent = round((100 * $pow['wins'] / ($pow['wins'] + $pow['loses'])));

but that spat out

Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean

I think the % calculation can be done within the main query rather than a php sum which I think would do it but I don't know what that query is.

like image 224
Anna Riekic Avatar asked Jan 16 '23 14:01

Anna Riekic


1 Answers

Instead of computing percentage value inside loop and then sorting using another loop, you can do it in just one query as:

$query  = "SELECT foo.*,
                  ROUND((100 * wins / (wins + loses))) AS percentage
           FROM foo
           WHERE foobar='{$fobo}'
           ORDER BY percentage ASC";

$result = mysql_query($query);

while($row = mysql_fetch_array($result))
{
   echo 'blah blah blah' . $row['percentage'];
}
like image 124
Omesh Avatar answered Jan 28 '23 11:01

Omesh