在php中将while循环的结果相乘

时间:2014-05-02 08:57:50

标签: php while-loop

所以我在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>';
    }

3 个答案:

答案 0 :(得分:1)

在循环外创建一个变量,并将其递增:

$count=0
while($row = $result->fetch_assoc()){
     $count+=$row['quantity'];
}
echo $count;

答案 1 :(得分:1)

完全按照你所写的内容完成:

$totalQTY = 0
while (....) {
   //...all your code....
   $totalQTY += $row['QTY']; // you didn't give the name of the column
}

答案 2 :(得分:1)

$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
}

只需添加一个计数器变量:)