doumi6685 2017-09-06 17:43
浏览 117
已采纳

使用MySQL的SubTotal在PHP中创建总计

I have a problem about make total in PHP.

I'd like to make total in my Web App (PHP based) but I get subtotal from database MySQL. And I will print it into table.

Here it is my code :

<table class="ui single selectable table">
  <tbody>
    <?php
    $idTrx = $_POST['idTrx'];
    $idUser = substr($idTrx, 3);
    $total;

    $query = "select trx.id_trx, tempTrx.id_user,  tempTrx.nameProduct as nameProduct, tempTrx.price as price, tempTrx.qty as qty, tempTrx.subtotal as subtotal from trx,tempTrx where (trx.id_trx='" . $idTrx . "' and trx.status='1') and tempTrx.id_user='" . $idUser . "';";

    $result = mysqli_query($link, $query);


    while ( $data = $result->fetch_array(MYSQLI_ASSOC) ) {
      echo "<tr><td>x</td><td>".$data['nameProduct']."</td><td>".$data['price']."</td><td>"
        .$data['qty']."</td><td>".$data['subtotal']."</td></tr>";

      for ($i=0; $i < count($data) ; $i++) { 
        $total += $data['subtotal'];
      }
    }

    ?>
  </tbody>
  <tfoot>
    <tr>
      <th>
        Total
      </th>
      <th></th>
      <th></th>
      <th></th>
      <th><?php echo $total ?></th>
    </tr>
  </tfoot>
</table>

I don't know how to make total from $data['subtotal'] with specific amount of $data.

After I added $total += $data['subtotal'];, I still don't get correct $total from it.

  • 写回答

2条回答 默认 最新

  • douwen5951 2017-09-06 18:42
    关注

    To get the correct value for $total, just add the value from $data['subtotal'] to $total, for each value returned from query. The for loop is not needed because you are going through each result from the query in the while loop. The way you have it now, it is adding the current value for $data['subtotal'] to $total multiple times (one for every count($data). So if count($data) is 10, it is adding the value for $data['subtotal'] 10 times per each row. Simply add the current value for $data['subtotal'] to $total.

    change

    for ($i=0; $i < count($data) ; $i++) { 
        $total += $data['subtotal'];
    }
    

    To

    $total += $data['subtotal'];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?