如何获取表格中的总行数?

时间:2016-08-28 04:55:50

标签: javascript php mysql

如何获得购物车的总金额并将其放在桌子下面的总数上?我应该使用JavaScript还是只使用PHP?请给我一些建议。谢谢。

      <thead>
        <tr>
          <th class="text-center">Product ID</th>
          <th class="text-center">Product Name</th>
          <th class="text-center">Description</th>
          <th class="text-center">Quantity</th>
          <th class="text-center">Price per Unit</th>
          <th class="text-center">Total Amount</th>
        </tr>
      </thead>
      <tbody>


      <?php 

        $selectCart = "SELECT * FROM cart INNER JOIN products ON products.product_id = cart.product_id";
        $execSelectCart = mysqli_query($connection, $selectCart);

        while ($row = mysqli_fetch_array($execSelectCart)) {

          $cartProId = $row['product_id'];
          $cartProName = $row['product_name'];
          $cartProDesc = $row['description'];
          $cartSellPrice = $row['sell_price'];
          $cartQty = $row['quantityCart'];

          $compute = $cartSellPrice * $cartQty;
          $totalAmount = number_format((float)$compute, 2, '.', '');
       ?>

        <tr>
          <td class="text-center"><?php echo $cartProId; ?></td>
          <td class="text-center"><?php echo $cartProName; ?></td>
          <td class="text-center"><?php echo $cartProDesc; ?></td>
          <td class="text-center"><?php echo $cartQty; ?></td>
          <td class="text-center"><?php echo $cartSellPrice; ?></td>
          <td class="text-center"><?php echo $totalAmount ?></td>
          </td>
        </tr>

      <?php } ?>
      </tbody>
    </table>
    <hr>
    <div class="row text-right">
      <div class="col-xs-2 col-xs-offset-8">
        <p>
          <strong>
            Sub Total : <br>
            VAT 12% : <br>
            Total : <br>
          </strong>
        </p>
      </div>
      <div class="col-xs-2">
        <strong>
          $36.00 <br>
          N/A <br>
          <?php echo $totalAmount; ?> <br>
        </strong>
      </div>
    </div>
   </div>

这是我的桌子。你可以看到,当我在while循环之外回显$totalamount时,它只会到达最后一行。

3 个答案:

答案 0 :(得分:2)

这适用于您的情况。

<?php 

        $selectCart = "SELECT * FROM cart INNER JOIN products ON products.product_id = cart.product_id";
        $execSelectCart = mysqli_query($connection, $selectCart);

        $totalAmount = 0;
        while ($row = mysqli_fetch_array($execSelectCart)) {

          $cartProId = $row['product_id'];
          $cartProName = $row['product_name'];
          $cartProDesc = $row['description'];
          $cartSellPrice = $row['sell_price'];
          $cartQty = $row['quantityCart'];

          $compute = $cartSellPrice * $cartQty;
          $totalAmount += number_format((float)$compute, 2, '.', '');
       ?>

答案 1 :(得分:0)

$total_amount = 0设置在循环上方。

在你的循环中添加:

$total_amount += number_format((float)$compute, 2, '.', '');

这将添加到$total_amount

您目前正在通过循环的每次互动重置总金额值。

答案 2 :(得分:0)

您可以设置$total_amount = 0并在while循环中确保将增量添加到总量(如$total_amount += $compute中,只需确保在进行增量之前将数字浮动。只需简单