Hi everyone

Don't know if someone can help me with my problem.

I'm trying to get a total from a loop variable name($cost), I'm running a for loop, thats getting values from mysql, all that i need is for the $cost value to be added up.

Code example:

$sql="select * from table";
$result=mysql_query($sql)or die(mysql_error());
$rows=mysql_num_rows($result)or die(mysql_error());

for($i=0; $i<$rows; $i++){
        $calld=mysql_result($result, $i, 'calldate');
        $dst=mysql_result($result, $i, 'dst');
        $duration=mysql_result($result, $i, 'duration');
	$todescr=mysql_result($result, $i, 'ToDescr');
	$cost=mysql_result($result, $i, 'CallCost');
}

Give's this in output.

Date Time Dailed Number Location AccCode Duration Cost
2008-05-05 08:47:48 0126747276 Pta 6600 00:00:33 R 0.32
2008-05-05 09:44:55 0798823159 Vodacom 6600 00:00:42 R 1.31
2008-05-05 09:49:08 0798823159 Vodacom 6600 00:01:07 R 2.09
2008-05-05 09:52:35 0825217925 Vodacom 6600 00:00:22 R 0.69
2008-05-05 10:06:45 0732430995 Mtn 6600 00:00:46 R 1.43

As I mentioned in another thread, have another variable array in the for loop, say, $cost_array. Assign the same value to it. Then do array_sum($cost_array). That will give you the sum of $cost.

Okay! Here is an example.

$sql="select * from table";
$result=mysql_query($sql)or die(mysql_error());
$rows=mysql_num_rows($result)or die(mysql_error());
$cost_array = array();
for($i=0; $i<$rows; $i++){
$calld=mysql_result($result, $i, 'calldate');
$dst=mysql_result($result, $i, 'dst');
$duration=mysql_result($result, $i, 'duration');
$todescr=mysql_result($result, $i, 'ToDescr');
$cost=mysql_result($result, $i, 'CallCost');
$cost_array[]=mysql_result($result, $i, 'CallCost');
}
$total = array_sum($cost_array);
echo $total;

Cheers,
Naveen

Hi Naveen

Thanks for your help.

It's working 100%

Thanks again
Cheers

You are welcome :)

Threads merged

@itsense please do not multipost same question and use code tags please

hye everyone...i want to ask if someone can help me to do student marks calculation... for example mark 4 history is 60 and mark 4 science is 70. i want to do automatically generate total marks 4 2 subject using php coding... Can somebody help me??

commented: Why bump a 1.5 year old, unrelated thread? +2
commented: Are we supposed to teach you addition ? -1
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.