Go through database to get me the total

0

Good I am taking out a message in case the client has a pending invoice but at the time to do the sum of the totals I am not able to do that I grouped them. Because if there are two products in an order, two lines are created in the database, so when added, it adds twice the same.

$us = $res['IdUsuario'];

$pedidos = $mysqli->query("SELECT Total, FORMAT(SUM(Total), 2) as suma, estadoFact, Iduser, id, pedidoid FROM pedidos WHERE estadoFact = 0 AND Iduser = $us");
   $ped = $pedidos->fetch_array();
   $esta = $ped['estadoFact'];
   $aban = $ped['abandonado'];

   for ($i=0; $i < sizeof($ped['estadoFact']); $i++) {
     if($aban[$i] == 0){
      echo "<div class=\"col-12 cuadroImpago\">
               <h2>Tienes Facturas pendientes</h2>
               <p>Dirijete a Facturación y abonalas para impedir cortes de servicio</p>
               <h3>" .$ped['suma']."</h3>
             </div>";
           }
        }

The idea of the for is to go through it, but something I will not be doing right.

    
asked by Miguel 14.12.2018 в 11:28
source

1 answer

0

This consultation could be worth:

SELECT p.Total, FORMAT(SUM(p.Total), 2) as suma, p.estadoFact, p.Iduser, p.id, p.pedidoid 
  FROM (SELECT Total, estadoFact, Iduser, id, pedidoid  
          FROM pedidos
         WHERE estadoFact = 0 
           AND Iduser = $us
         GROUP BY pedidoid 
        ) as p

Basically, it is a question of grouping first the field / s you need and then making the SELECT on those data already grouped, so duplicates will be discarded.

Depending on the case, a 'DISTINCT' ( link could also be valid) )

You have more information in the SUBCONSULTAS section of the official mysql documentation

    
answered by 14.12.2018 / 15:04
source