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.
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'];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With