Subtract fields inside while in PHP

Asked

Viewed 48 times

0

I am having difficulty subtracting fields from the same column (measurement), I have date, time and measurement in a table called reading.

I want it to stay that way:

data, hora, medicao, consumo  
06/09, 10:00, 200, 0  
07/09, 10:00, 210, 10  
08/09, 10:00, 235, 25  
09/09, 10:00, 290, 55  

Always taking the medication of the day and subtract with the previous day and inform the result, the field consumption does not exist in the bank.

That has to be inside the while.

$sqlbuscar = "SELECT data, hora, medicao FROM medicoes";
$result = mysqli_query($conexao, $sql);

while ($linha = mysqli_fetch_array($result)) {
    $linha["0"];  
    $linha["1"];  
    $linha["2"];  
    $consumo;     
}

2 answers

0


When the measurement does not exist, define using the first one, then keep the one that is set. Then only use in the consumption calculation. I slightly changed your code and added some comments.

$sqlbuscar = "SELECT data, hora, medicao FROM medicoes";
$result = mysqli_query($conexao, $sql);
$consumo = null;
$medicao = null;
while ($linha = mysqli_fetch_array($result)) {
    // Quando a medição não existe, define usando a primeira, depois mantém a que estiver definida
    $medicao = ($medicao ? $medicao : $linha["2"]);
    $linha["0"];  
    $linha["1"];  
    $linha["2"];  
    $consumo = ($linha["2"] - $medicao);
    // define a medição para o cálculo do consumo na próxima linha
    $medicao = $linha["2"];
    echo $consumo;    
}

0

Benilson thanks worked perfect!

also put to display the total consumption.

$total consumption += $consumption;
echo $totalConsume;

Browser other questions tagged

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