How to sum the values of a column, also adding the decimals in PHP?

-1

How can I calculate the sum of the values of a column by considering the decimal values (after points and commas) with PHP .

I used in select o SUM() but the sum returned only integers. I need a way that adds the miliaries and decimals.

My code:

 <?php 
 $id_cadastro = $_GET['cad'];
 $lista_valor = mysql_query("SELECT SUM(valor_sessao) AS soma_total FROM procedimentos_evolucao_geral WHERE id_paciente='$id_cadastro'");
 $conta_valor = @mysql_num_rows($lista_valor);
 if($conta_valor <=0){ 
    echo ''; 
 }else{ 
    while($linhaT_valor= mysql_fetch_array($lista_valor)){ 
        $valor_total = $linhaT_valor['soma_total'];
    }
 }
 echo $valor_total; 
 ?>

Registered values are 5, 5, and 5.50 and are returning only 15 instead of 15.50.

    
asked by anonymous 03.04.2018 / 00:23

1 answer

0
  

Junior, the real solution is not to store in the database as a string, which causes problems at various scales. The ideal is to store as decimal, and format with comma only in the parts that display on the screen. (Bacco)

But if it is not feasible to change the structure and you want to opt for a punctual solution, you can do this:

  • REPLACE - comma-to-point exchange REPLACE(valor_sessao,',','.')
  • CAST - Converts an expression of a type data to another
  • DECIMAL
  • PHP

        $id_cadastro = $_GET['cad']; 
    
        $lista_valor = mysql_query("SELECT SUM(CAST( REPLACE(valor_sessao,',','.') as DECIMAL(6,2))) AS soma_total FROM procedimentos_evolucao_geral WHERE id_paciente='$id_cadastro'");
    
         $conta_valor = @mysql_num_rows($lista_valor); 
         if($conta_valor <=0){ 
            echo ''; 
         }else{ 
            while($linhaT_valor= mysql_fetch_array($lista_valor)){ 
                $valor_total = $linhaT_valor['soma_total']; 
            } 
    
         } 
         echo $valor_total;
    

    Sample table:

    Result:

        
    03.04.2018 / 15:19