php – Add values ​​from a select when repeating the client id

Question:

How could I add the values ​​of a select when it repeats the client's id?

Example

I 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:

Manuel – BRL 20.00

Manuel – BRL 40.00

Isac- R$60.00

Isac- R$40.00

João- R$40.00

As I need it to be adding the values ​​without repeating the names of the clients:

Manuel – BRL 60.00

Isac- R$100.00

João- R$40.00

Answer:

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
Scroll to Top