添加While循环计算的值以给出总计

时间:2014-06-11 10:31:21

标签: php mysql

我有这样的声明:

result2 = mysqli_query($con,"SELECT ID, QTY, 
DESCRIPTION, UNIT_PRICE, LINE_TOTAL, CONNECT FROM b_po_line 
WHERE CONNECT = $ID");

while($row = mysqli_fetch_array($result2))
{
$qty = $row['QTY'];
$description = $row['DESCRIPTION'];
$unitPrice = $row['UNIT_PRICE'];
$lineTotal = $row['QTY']*$row['UNIT_PRICE'];

<tr><td>$qty</td><td>$description</td><td>$unitPrice</td><td>number_format($linetotal,2)</td></tr>

}

这绝对没问题。我需要做的是将$ linetotal的值加起来,以便它给出一个总答案,无论是返回一个结果还是十个。我不知道如何计算。

我们将不胜感激。

5 个答案:

答案 0 :(得分:1)

$total=0;
while($row = mysqli_fetch_array($result2))
{
$qty = $row['QTY'];
$description = $row['DESCRIPTION'];
$unitPrice = $row['UNIT_PRICE'];
$lineTotal = $row['QTY']*$row['UNIT_PRICE'];
$total += $lineTotal;
echo '<tr><td>' .$qty . '</td><td>' . $description . '</td><td>' . $unitPrice . '</td><td>' .number_format($lineTotal,2) . '</td></tr>';

}

答案 1 :(得分:1)

如果您想这样计算,请将一个变量初始化为0

例如: $total_lineitems = 0;

然后将此值更新为$lineTotalwhile循环的总和,

$total_lineitems  += $lineTotal;

此外,您无法在php代码中直接编写html。最好与字符串连接并打印出来。

echo '<tr><td>' .$qty . '</td><td>' . $description . '</td><td>' . $unitPrice . '</td><td>' .number_format($lineTotal,2) . '</td></tr>';

而不是

<tr><td>$qty</td><td>$description</td><td>$unitPrice</td><td>number_format($linetotal,2)</td></tr>

试试这个

$total_lineitems = 0;

while($row = mysqli_fetch_array($result2))
{
   $qty = $row['QTY'];
   $description = $row['DESCRIPTION'];
   $unitPrice = $row['UNIT_PRICE'];
   $lineTotal = $row['QTY']*$row['UNIT_PRICE'];

   $total_lineitems  += $lineTotal;

    echo '<tr><td>' .$qty . 
         '</td><td>' . $description . 
         '</td><td>' . $unitPrice . 
         '</td><td>' .number_format($lineTotal,2) . 
         '</td></tr>';
}

echo $total_lineitems ;

答案 2 :(得分:1)

<?php
$grandtotal = 0;

for($i=0;$i<10;$i++){
$grandtotal += $i;
}

echo $grandtotal;
?>

答案 3 :(得分:0)

在while循环之前初始化变量,并将其增加为每个cicle中的linetotal值。

答案 4 :(得分:-3)

做这样的事情

result2 = mysqli_query($con,"SELECT ID, QTY, 
DESCRIPTION, UNIT_PRICE, LINE_TOTAL, CONNECT FROM b_po_line 
WHERE CONNECT = $ID");
$total = 0;
while($row = mysqli_fetch_array($result2))
{
   // old code as it is

   $total+=$linetotal;


}
 echo $total;