• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

[PHP/MYSQL] Calculate percentage problem

FromHollandWithLove

Junior Member
Hi, i am writing my own webstats script and have encountered the following problem.
I extract referring domains from the stats database with the following query:

$ref_query="SELECT Count(*) as aantal1, ref_domein FROM pageviews
WHERE ref_domein != 'odessa.nl' AND ref_domein != 'none'
Group By ref_domein order by aantal1 desc";

Subsequently, i write a table containing the domains ($ref_domein) on the left and the amount of hits per domain ($aantal1) on the right. Like this:

echo "<table bgcolor='#000000' cellpadding='2' cellspacing='1' border='0'>";
echo "<tr><td colspan='3' bgcolor='#CEF4FD'><font color='#000066'>Ref domains</font></td></tr>";

while($q=mysql_fetch_array($result_ref))
{
$aantal1=$q["aantal1"];
$totaal += $aantal1;
$ref_domein=$q["ref_domein"];



echo "<tr bgcolor='#f5f5f5'><td>$ref_domein</td><td>$aantal1<td/></tr>";
}
echo"<tr><td colspan='2' align='right' bgcolor='#ffffff'>$totaal</td></tr>";

echo "</table>";

An example can be viewed at the bottom of this page: http://www.odessa.nl/internetdelen/stats.php

Now, i want to calculate the percentages of the total amount of hits instead of the amounts. The problem is, that i already need $total at the moment i start calculating the first percentage, while $total now becomes available at the end of the table. Can you help me out?
 
Instead of selecting count(*) in your query you could try doing something like this:

SELECT (100 * COUNT(*)/(SELECT COUNT(*)
FROM pageviews
WHERE ref_domein != 'odessa.nl'
AND ref_domein != 'none')) AS aantal1
,ref_domein
FROM pageviews
WHERE ref_domein != 'odessa.nl'
AND ref_domein != 'none'
GROUP BY ref_domein
ORDER BY aantal1 DESC

I've never used MySQL, but hopefully this will work and it should return you the percentages of total hits.

Edit, messed my brackets up
 
I don't think I totally understand the issue, but you could do an extra query for the total # of hits, or you could feed the query into an array first, then do whatever you want with the array (although that's kinda bloaty).
 
Back
Top