How to add PHP values inside a "for" to bring the total

Asked

Viewed 436 times

1

I have the following schedule, which brings the price of each selected item:

for($x=1;$x<=4;$x++){
    if($_POST['p'.$x] != '0'){
    $sql = "SELECT produto, preco FROM produtos WHERE p = '".$px."'";
    $result = $db->query($sql);
    $obj = mysqli_fetch_object($result);
    $preco = $obj->preco;
    echo $preco.'<br/>';
    }
}

He brings for example:

10
11
15

I wish that after I brought all this up he’d put it all together in another variable to bring:

10
11
15
36

How can I do?

1 answer

4


Simple, declares a variable outside of the for, and sums it inside the for.

By following your code:

$total = 0;

for($x=1;$x<=4;$x++){
    if($_POST['p'.$x] != '0'){
    $sql = "SELECT produto, preco FROM produtos WHERE p = '".$px."'";
    $result = $db->query($sql);
    $obj = mysqli_fetch_object($result);
    $preco = $obj->preco;

    $total += $preco;

    echo $preco.'<br/>';
    }
}
  • Perfect, I figured it could be something really simple, thank you very much!

Browser other questions tagged

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