Page 1 of 1

Calculating Percentage Help?

Posted: Sat Mar 22, 2008 4:13 pm
by jc_ply
Hey guys having a bit of trouble with by flash back end (mySQL) and was wondering if you could share the wisdom?

I always feel illustration helps so heres my table...(called war)...dont ask

war_id | times_selected
1 | 5
2 | 3
3 | 9
4 | 17
5 | 3

Basically I need to select the highest value of times_selected (17 for example but is actually a counter updated from flash) and find its percentage to return along with its "war_id (4)

My psudeo code was along the lines of

-----

SELECT SUM(times_selected) as "Total"
FROM war

($Highest value of times_selected / "Total" x 100 = $var

PRINT $highest value war_id, $var (its percentage)

-----

As you can tell im not too hot with the PHP/mySQL right now and have been pouring over syntax combinations on and off for a while with no success. Also the print is to return it to flash as im sure you know.

Any help would be greatly appreciated.

Jason

Re: Calculating Percentage Help?

Posted: Sat Mar 22, 2008 8:18 pm
by califdon
Your concept is okay, but of course you will have to execute the query and extract the total selections, and you will need to know the number of selections of the maximum war. Maybe something like this:

Code: Select all

$sql="SELECT SUM(wars_selected), MAX(wars_selected) FROM war";
$result=$mysql_query($sql);
$row=mysql_fetch_array($result);
$total=$row[0];
$top=$row[1];
$pct=$top / $total * 100;
$sql="SELECT war_id FROM war WHERE wars_selected = $top";
$result=$mysql_query($sql);
$row=mysql_fetch_array($result);
$id=$row[0];
echo "ID# $id scored tops with $top selections, which is $pct % of the total selections";
That's only a rough start. It will fail if more than one person has the same top score, and you'd no doubt want to format your percentage so it doesn't show something like "18.668035917%".

Re: Calculating Percentage Help?

Posted: Sat Mar 22, 2008 10:20 pm
by jc_ply
Thanks califdon you steered me onto the right track.