Add values from a select when repeating the client id

4

How could I sum the values of a select when it repeats the client id?

Example

Use this select:

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT * FROM clientes";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo  $row["nome"]. " - " . $row["valor"]. "<br>";
    }
} else {
    echo "0 results";
}
$conn->close();

Result:

  

Manoel - $ 20.00

     

Manoel - R $ 40,00

     

Isac- $ 60.00

     

Isac- $ 40.00

     

John- $ 40.00

How do I need to add the values without repeating the names of the clients:

  

Manoel - $ 60.00

     

Isac- $ 100.00

     

John- $ 40.00

    
asked by anonymous 28.12.2018 / 11:54

2 answers

5

You need to use SQL group by .

For the result you want the query would be:

SELECT nome, SUM(valor) valor FROM clientes GROUP BY nome;
    
28.12.2018 / 12:09
2

Group the result by user name using the GROUP BY clause and use the SUM function to add these grouped results.

Modify your query to stay as follows:

$sql = "SELECT nome, SUM(valor) FROM clientes GROUP BY nome";

In the link I am leaving below, you have a very complete answer of how this GROUP BY of SQL clause works.

Link: #

    
28.12.2018 / 12:14