Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Sum of an Array

Status
Not open for further replies.

Tuck007

Technical User
Apr 29, 2002
105
US
Is there a way to get the sum of all the values in an array, from a MySQL database?? Look at this snippet:
Code:
67<?php 
68if(!empty($result)){
69	while ($myrow = mysql_fetch_array($result)) {
70		echo &quot;<tr>&quot;;
71		printf(&quot;<td bgcolor=\&quot;#FFFFFF\&quot; align=\&quot;center\&quot;>%s</td>&quot;, $myrow['id']);
72		printf(&quot;<td bgcolor=\&quot;#FFFFFF\&quot; align=\&quot;center\&quot;>%s</td>&quot;, $myrow['date_time']);
73		printf(&quot;<td bgcolor=\&quot;#FFFFFF\&quot; align=\&quot;center\&quot;>%s</td>&quot;, $myrow['name']);
74		printf(&quot;<td bgcolor=\&quot;#FFFFFF\&quot; align=\&quot;center\&quot;>%s</td>&quot;, $myrow['items']);
75		printf(&quot;<td bgcolor=\&quot;#FFFFFF\&quot; align=\&quot;center\&quot;>%s</td>&quot;, $myrow['mgr']);
76		printf(&quot;<td bgcolor=\&quot;#FFFFFF\&quot; align=\&quot;center\&quot;>%s</td>&quot;, $myrow['hws']);
77		printf(&quot;<td bgcolor=\&quot;#FFFFFF\&quot; align=\&quot;center\&quot;>%s</td>&quot;, $myrow['leads']);
78		printf(&quot;<td bgcolor=\&quot;#FFFFFF\&quot; align=\&quot;center\&quot;>%s</td>&quot;, $myrow['CPO']);
79		echo &quot;</tr>&quot;;
80		}
81	}
82
83$total = sum($myrow['CPO']);
84
85echo &quot;<tr>&quot;;
86printf(&quot;<td colspan=&quot;6&quot;></td><td bgcolor=\&quot;#FFFFFF\&quot; align=\&quot;center\&quot;>Total</td><td bgcolor=\&quot;#FFFFFF\&quot; align=\&quot;center\&quot;>$total</td>&quot;);
87echo &quot;</tr>&quot;;
88?>
In line 83 I'd like $total to contain the sum of all the values in $myrow['CPO'], kind'a like in an excel sheet. In my database, feild CPO contains integer values. Can I do that or am I just nuts? .:TUCK:.
 
How 'bout this?

Remove line 83;

Add this line after line 79:
$total += $myrow['CPO'];

Add this line after line 68:
$total = 0;


Or were you looking for something else?


 
Let me give it a go, I think that may do what I wanted. .:TUCK:.
 
That looks good, and works fine! If I understand the process right, it gives $total a zero value everytime it opens, begins adding a value each time the loop goes through, and it will recalculate the value for $total everytime the page is loaded? .:TUCK:.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top