开发者

Adding up total of mysql_num_rows in a while loop

开发者 https://www.devze.com 2023-04-13 05:26 出处:网络
For example I have a mysql_num_rows results of 4,8,15,16,23,42 in a query that is inside a while loop of another query. My question is how can I total all the results inside that while loop? 开发者_Go

For example I have a mysql_num_rows results of 4,8,15,16,23,42 in a query that is inside a while loop of another query. My question is how can I total all the results inside that while loop? 开发者_Go百科(Total of 133) Thanks.

EDIT:

How about if I want to get the percentage per each result of mysql_num_rows inside my while loop? Example: 4,8,15,16,23,42. Total is 108. $sum = 108. Percentage of 4 = 4/$sum = 3.7%, 8 = 8/$sum = 7.4% and so on..


Try something like this:

$Sum = 0;
while ($SomeInvariant)
{
   mysql_query($SomeQuery);
   $Sum += mysql_num_rows();
}

echo 'The sum is: ' . $Sum;

However, this approach is not very efficient (what if $SomeInvariant is true for many iterations, and your app has even more concurrent users?). To account for this, I would recommend restructuring your approach so the addition is done in SQL. This way, your query could look something like this: SELECT SUM(ColumnName) FROM ....

UPDATE: Addressing follow-up question in the comments

If you don't already have the sum available from the query, then you'll have to loop over the dataset twice. On the first pass, you'll calculate the sum. On the second pass, you'll calculate the ratio of each value to the sum.

For example:

$Sum = 0;
$Rows = array();
while ($SomeInvariant)
{
   mysql_query($SomeQuery);
   $Value = mysql_num_rows();
   $Rows[] = $Value; // Push the value onto the row array
   $Sum += $Value;   // Add the value to the cumulative sum
}

echo 'The sum is: ' . $Sum;

foreach ($Rows as $Row)
{
    echo $Row . '/' . $Sum . ' = ' . number_format($Row / $Sum) . '%';
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号