2017-03-14 30 views
0

我現在有一段代碼,我想基本上是拉動產品的數量和價格,然後給我有一個總計PHP MySQL的雙While循環給我的問題

的問題是數學偏了..它實質上是將最後一個數量乘以循環中物品的最後價格(我希望我解釋說至少有半盎司的淨度哈哈!)

反正這裏是代碼,我認爲它是沿着正確的行,但在某個地方我出錯了,謝謝!

<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

使用'join',那麼你將不需要第二個循環。 – chris85

+0

循環查詢總是一個糟糕的主意。你可以在一個查詢中做到這一點 –

+0

$ linetotal = $ priceline * $ linequantity; ,因爲您事先使用了一段時間,它只會將最後一個priceline值帶到這條linetotal –

回答

1

您可以通過在循環中添加$linetotal來計算總計。

$total=$total+$linetotal; 

在循環之前用0初始化$total