1.11M Members

echo field with sum of different fields

 
0
 

Hi

I have to echo out some fields but "field 1" "field 2" "field 3" has a numeric value.

I need to divide field 1 by field 2 and then take that result off of field 3 and echo that result.

The code is part of a table this is the code for that row

Hope someone can help

 echo '<td>' . $row['field3'] . '</td>';
 
0
 

Maybe this helps:

$result = $row['field1'] / $row['field2'];
echo "<td>".$result."</td>";

Why do you need field3 ?

 
0
 

This is simple maths, use parentheses to force calculations in correct order:
field3 minus (field1 divided by field2)

$result = ( $row['field3'] - ($row['field1'] / $row['field2']) );
echo "<td>".$result."</td>";
 
0
 

HI Thanks for the help but the error comes up as Warning: Division by zero

 
0
 

I have now fixed that with a @ before the brackets

Now I get the error of resource id# where the result should echo.

Can you help?

 
0
 

Probably can help, but need to see the rest of your code to understand why there is an error.

 
0
 

All the code is very large so I will go over what I am doing

resource is in the head
$result = ( $row['field3'] - ($row['field1'] / $row['field2']) );

i am echoing a table out with all the info in with a query and while($row = mysql_fetch_array($result))

with loads of rows, and one of those rows is your code

echo '<td>'.$result.'</td>';

Hope this is ok for the info

 
0
 

You could do a calculated field within the SQL itself:

SELECT field1, field2, field3, field3 - (field1/field2) AS calc FROM table

Obviously if field2 is empty, you'll get an error as you can't divide by zero.

 
0
 

HI thanks for your reply , where would I put that please as i already have a query for my table

Thanks

 
0
 

Hey that's plenty info.
The line needs to be in the while loop (it will change every time), so put it under the line:

while($row = mysql_fetch_array($result)){
    $total = ( $row['field3'] - ($row['field1'] / $row['field2']) );
    //then in the place you want the total to show:
    echo "<td>".$total."</td>";

This presumes your column names really are 'field1', 'field2' and 'field3', if not adjust accordingly. Diafol's idea was good too, well worth investigating, but you would need to show your existing query for instruction on that front.

 
0
 

brilliant that owkrs perfect. Now only problem is i need 2 decimal points not 10 please :)

Thanks

 
0
 

Its ok thanks for your help I sorted the decimal point thing

for anyone else

'.sprintf("%.2f",$total).'

Question Answered as of 1 Year Ago by adam.adamski.96155, diafol and last1devil
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article