[英]Multiplying results of while loop in php
所以我在php中有一個while循環,我將每條記錄從mysql數據庫中拉出,效果很好,但是我現在要做的是將QTY列的結果加在一起以得到總數,但是我不是確保每次將while循環循環時如何將每個結果加在一起,從而擦除最后一個循環。
例如,如果我有以下記錄:
ID QTY NAME
1 2 BOX1
2 54 BOX2
3 21 BOX6
當我在while循環中將它們回顯時,它們的效果與上面相當。 我想做的是每次將QTY加到總計中,這樣我就可以獲得QTY總計,並將其用作$ totalQTY。
$sql = <<<SQL
SELECT * FROM `orders` WHERE `orderid` = '$view' AND `isline` = 'no'
SQL;
if(!$result = $db->query($sql)){ die('There was an error running the query [' . $db->error . ']');}
while($row = $result->fetch_assoc()){
echo '<h2>Order Id : '.$row['orderid'].'</h2>';
echo '<p><strong>Customer Order Number : '.$row['customerordernumber'].'</strong></p>';
echo '<p><strong>Order Date :</strong> '.date("d/m/Y H:i:s", strtotime($row["orderdatetime"])).'</p>';
echo '<p><strong>Order Notes :</strong> '.$row['ordernotes'].'</p>';
echo '<p><strong>Label Type :</strong> '.$row['labeltype'].'</p>';
echo '<p><strong>Trolley Type :</strong> '.$row['trolleytype'].'</p>';
echo '<p><strong>Deliver By :</strong> '.$row['deliverby'].'</p>';
echo '<p><strong>Ordered Items : </strong></p>';
}
在循環外創建一個變量,並將其遞增:
$count=0
while($row = $result->fetch_assoc()){
$count+=$row['quantity'];
}
echo $count;
只需按照您寫的內容做即可:
$totalQTY = 0
while (....) {
//...all your code....
$totalQTY += $row['QTY']; // you didn't give the name of the column
}
$sql = <<<SQL
SELECT * FROM `orders` WHERE `orderid` = '$view' AND `isline` = 'no'
SQL;
if(!$result = $db->query($sql)){ die('There was an error running the query [' .$db->error . ']');}
$totalqty=0; // add this
while($row = $result->fetch_assoc()){
echo '<h2>Order Id : '.$row['orderid'].'</h2>';
echo '<p><strong>Customer Order Number : '.$row['customerordernumber'].'</strong></p>';
echo '<p><strong>Order Date :</strong> '.date("d/m/Y H:i:s", strtotime($row["orderdatetime"])).'</p>';
echo '<p><strong>Order Notes :</strong> '.$row['ordernotes'].'</p>';
echo '<p><strong>Label Type :</strong> '.$row['labeltype'].'</p>';
echo '<p><strong>Trolley Type :</strong> '.$row['trolleytype'].'</p>';
echo '<p><strong>Deliver By :</strong> '.$row['deliverby'].'</p>';
echo '<p><strong>Ordered Items : </strong></p>';
$totalqty+=intval($row['QTY??']); //your field value must be changed add this
}
只需添加一個計數器變量如上:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.