Start New Discussion within our Web Development Community


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>';

Maybe this helps:

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

Why do you need field3 ?

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>";

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

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?

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

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.

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


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.

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


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

for anyone else


This question has already been answered. Start a new discussion instead.