Add specific keys obtained in SQL query - PHP

Asked

Viewed 154 times

0

I have an sql query that returns all the fields of a table :

$registro = mysqli_query($con, "SELECT * FROM agenda ORDER BY procedimento LIMIT $limit, $nroLotes");

My doubt is, if it is possible, through this query, to add the values of a certain column, associated to the values of another column, ex:

Among other columns there are "Column : Name" where the values are names and "Column : Value" where the values are numbers. The idea is to add the values associated with the names.

I imagine I should do a foreach inside the while, but I’m having difficulty in that approach.

Follows the excerpt from the code in question:

<?php
//...
$registro = mysqli_query($con, "SELECT * FROM agenda ORDER BY procedimento     LIMIT $limit, $nroLotes");
$tabela = $tabela.'<table class="table table-striped table-condensed table-  hover">
                    <tr>
                  <th width="300">Nome</th>
                  <th width="200">Procedimentos</th>
                  <th width="150">Valor Cobrado do serviço</th>
                  <th width="150">Valor Total dos serviços</th>
                  <th width="150">Porcentagem do Valor Total dos serviços</th>
                  <th width="150">Data</th>
                    </tr>';


while($linha = mysqli_fetch_array($registro)){
$porcentagem = ($linha['valor'] * 30) / 100;
$tabela = $tabela.'<tr>
                        <td>'.$linha['nome_funcionario'].'</td>
                        <td>'.$linha['procedimento'].'</td>
                        <td>'.number_format($linha['valor'], 2, ',', '.').'</td>
                        <td>'.number_format($porcentagem).'</td>
                        //célula que conterá a soma 
                        //<td>'.number_format($soma).'</td>
                        <td>'.fechaNormal($linha['start']).'</td>';     
}
$tabela = $tabela.'</table>';

$array = array(0 => $tabela,
               1 => $lista);

echo json_encode($array);
?>

1 answer

1


I may be mistaken, but you can achieve this in SQL itself using SUM() and GROUP BY.

Try running the following Query in your table (check the names of the fields if they are right):

SELECT *, SUM('valor') AS SomaValor FROM agenda GROUP BY 'nome' ORDER BY procedimento

See if the result of SomaValor is what you’re looking for.

  • In case I would have to put : $line['Somavalor']?

  • @Magichat yes, just make sure the Query is right, because I didn’t have time to test it, so I’m not sure.

Browser other questions tagged

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