PHP MySQL Dual While Loop给我带来了麻烦

时间:2017-03-14 16:21:43

标签: php mysql

我目前有一段代码,我希望从根本上提取产品数量和价格,然后给出总计

我遇到的问题是数学方法已经过时了......它基本上将最后一个数量乘以项目的最后一个价格(我希望我用至少半盎司的清晰度来解释)哈哈!)

无论如何这里是代码,我认为这是正确的行,但我出错了,谢谢!

<table>
      <tr>
    <th>Product Title</th>
    <th>Nicotine Strength</th>
    <th>Quantity</th>
    <th>Price (inc. VAT)</th>
  </tr>
    <?php 
    $query = "SELECT `product`, `variant`, `quantity` FROM orders_detail WHERE order_id = '$orderid'";
    $result = mysqli_query($con, $query);
    $quantitytotal = 0;
    while ($row = mysqli_fetch_assoc($result)) {
        $product = $row['product'];
        $stuff = $row['quantity'];
        $variant = $row['variant'];
        $linequantity = $stuff;
        $quantitytotal += $stuff;


        $pricequery = "SELECT product_price FROM products WHERE product_name = '$product'";
        $priceresult = mysqli_query($con, $pricequery);
        $pricetag = 0;
        $priceline = 0;
        while ($rowprice = mysqli_fetch_assoc($priceresult)) {
            $price = $rowprice['product_price'];        
            $priceline = $price;
            $pricetag += $price;

        }
        echo "Price: $pricetag<br>";
        echo "Quantity: $quantitytotal<br>";
        $linetotal = $priceline * $linequantity;
        //echo "$product - $linequantity - $linetotal<br>";
        echo  '<tr><td>' . $product .' </td> ' . '<td>' . $variant . '</td>' . ' <td> ' . $linequantity . '</td>' . '<td> £' . $linetotal . '</td> </tr>';  

    }
    $total = $pricetag * $quantitytotal;
        ?> 



    <tr><td>Total Ex Vat:</td><td> Total Inc Vat:</td></tr>

    <tr><td><?php echo "£" . ($total / 1.2);?></td>
    <td><?php   echo "£" . $total; ?></td></tr>
</table>

1 个答案:

答案 0 :(得分:2)

您可以通过在循环中添加$linetotal来计算总计。

$total=$total+$linetotal;

在循环前将$total初始化为0。