Calculating Percentage Help?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
jc_ply
Forum Newbie
Posts: 5
Joined: Wed Mar 19, 2008 11:38 pm

Calculating Percentage Help?

Post 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
User avatar
califdon
Jack of Zircons
Posts: 4484
Joined: Thu Nov 09, 2006 8:30 pm
Location: California, USA

Re: Calculating Percentage Help?

Post 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%".
jc_ply
Forum Newbie
Posts: 5
Joined: Wed Mar 19, 2008 11:38 pm

Re: Calculating Percentage Help?

Post by jc_ply »

Thanks califdon you steered me onto the right track.
Post Reply