Add PHP results

-1

I searched but I can not find the solution.

I have the following code:

 <table class="table table-responsive">
 <thead class="text-center">
<th scope="col">Cantidad</th>
<th scope="col">Producto</th>
<th scope="col">Precio Unitario</th>
<th scope="col">Total</th>
<th scope="col">Acción</th>
 </thead>
<?php 
 foreach($_SESSION["carrito"] as $c):
      $products = $cnx->query("SELECT * FROM productos WHERE id_producto=$c[id_producto]");
 $r = $products->fetch_object();
     ?>
 <tr>
 <td scope="row"><?php echo $c["cantidad"];?></td>
<td><?php echo $r->nombre;?></td>
<td>$ <?php echo $r->preciototal; 
  ?></td>
    <td>$ <?php echo $c["cantidad"]*$r->preciototal; ?></td>
<td style="width:260px;">
 <?php
   $found = false;
     foreach ($_SESSION["carrito"] as $c) { if($c["id_producto"]==$r->id_producto){ $found=true; break; }}
     ?>
    <a href="../carrito/actions/delfromcart.php?id=<?php echo $c["id_producto"];?>" class="btn btn-danger">Eliminar</a>
  </td>
 </tr>

 <?php 

    echo $r->preciototal;
 endforeach; ?>
 </table>

Printing $r->preciototal; gives the results of the general foreach.

That is, I have 2 products, gives results of a total of 2 products.

I want those "preciototal" of each product, are added with their quantities and each other .. thus giving the TOTAL of everything.

That is:

$producto1 = 100;
$cantidadP1 = 2;
$totalP1 = 200;
$producto2 = 200;
$cantidadP2 = 3;
$totalP2 = 600;
$total = 800;
    
asked by Juan 14.02.2018 в 21:41
source

1 answer

0

Simply create a variable that adds up those totals, something like this:

$suma_total = 0;

and then in the foreach you add the totals:

$suma_total += $r->preciototal;

and out of the foreach you print the total variable

echo $suma_total
    
answered by 14.02.2018 / 22:01
source