PHP + SQL Add two values from the same column

Asked

Viewed 285 times

0

I have a table like this:

And I need to add the value of id 1 to the value of id 15, saving to a variable in PHP.

I’ve researched a lot but I couldn’t get anything specific to it. Thanks for any help!

NOTE: I have been trying the following but is returning 1, when it is right to return 49.14:

$result = mysqli_query($conn, "SELECT SUM(valor) FROM tb_valores WHERE id = ($id1) OR id = ($id15) ");

echo $linhasemuso = mysqli_affected_rows($conn);

3 answers

0

The logic is kind of simple, but it works, if you adapt, you can make a generator of querys and insert new Ids whenever necessary:

$execute = mysqli_query($conexao, "SELECT * FROM tabela_assim WHERE id = '$Id1' OR Id = '$Id2'");

$soma_total = 0;

while($line = mysqli_fetch_array($execute)){

$soma = $line['valor'];

$soma_total = $soma + $soma_total;
}

?>

  • Unfortunately, it didn’t work here. I did so: $execute = mysqli_query($Conn, "SELECT * FROM tb_values WHERE id = '$id1' AND id = '$id15'"); $soma_total = 0; while($line = mysqli_fetch_array($execute)){ $sum = $line['value']; $soma_total = $sum + $soma_total; } echo $soma_total; And it still doesn’t work...

  • A variable, in the id case, cannot be simultaneously equal to two distinct values. I believe you actually want to use the logical operator OR and not AND.

  • @anonimo It’s vdd, I was wrong about that part

0

inserir a descrição da imagem aqui

That’s the answer that works, but it’s a very big code, I’d like to narrow it down. Someone?

0


If someone is going through the same problem, here’s the answer:

inserir a descrição da imagem aqui

$result = mysqli_query($conn, "SELECT SUM(valor) AS conta FROM tb_valores WHERE id = 1 OR id = 15 ");
$row = mysqli_fetch_assoc($result); 
echo $sum = $row['conta'];

Browser other questions tagged

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