Direct sum in PHP

Asked

Viewed 261 times

1

I have a service control system. I would like to issue a service report and add up those figures but I did not want to do with the command on sql want to do right in the php, type sum of column values valor_trabalho only of the listed services

it would be like this

OS | DESCRICAO | VALOR

 1 |  visita   | 150,00

 2 |  visita   | 130,00

total = ???

my sql and so

$trabalho=mysql_query( "SELECT * FROM cad_trabalho WHERE id_trabalho = '$id'");`

use this function to display the data

<?php
while($row = mysql_fetch_object($trabalho)) {                                    
echo "<tr><td>$row->os</td><td>$row->descricao</td><td>$row->valor</td></tr>
      <tr>total = ???</tr>";
}
 ?>

1 answer

1


A simple example:

<?php
   $total = 0;
   while($row = mysql_fetch_object($trabalho)) {                                    
      $total += $row->valor;
      echo "<tr><td>$row->os</td><td>$row->descricao</td><td>$row->valor</td></tr>";
   }
   echo "<tr><td colspan="3">TOTAL: $total</td></tr>";
?>

This is clear, assuming $rou->valor is numerical. If string, depends on the format. It may be necessary to exchange a comma for a period, etc.

Just for the record, $total += $row->valor is the short way to write $total = $total + $row->valor

  • worked perfect now I’m only having error with the value that this gives me R$: 89978.856 because my saved values are like 350,66 1.253,00

  • It is basically what I commented, its values are stored in the wrong format, are written as string in DB. The right is to write in numeric, and put the commas and dots on the screen only in the display. As they are already recorded wrong, would have to use $total += strtr( strtr( $valor, '.', '' ), ',', '.' ); - But this is a painful gambit. It is right to fix the mistake instead of using a patch.

  • has some function to correct in the comic?

  • First of all, you’d have to back up the DB to avoid accidents. Then take out the dots, then swap the commas for dots, and convert the table to decimal. If it’s a new project, and the data is just a test, you don’t have to do all this work, just recreate the table with the value field or in integers (and store the value in cents, so you don’t need the point), or use the DECIMAL type, which is for financial values.

  • Here is an answer that talks a little about this: http://answall.com/a/104203/70

  • It already has over 1000 records :)

  • I would like you to help me on one more point here

  • My result is bringing me the following value R$: 237688.6how do I make it display R$: 237688.60

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.