我正在从数据库中获取数据,ID,名称和价格。但是while循环内部也是一个数量。我不知道如何捕捉每种产品的数量。该数量在while循环内与新产品重复。但是,如果我想在while循环之外捕获所有产品的数量,我只会得到一个值。我希望有人能给我答案(我是初学者)。
代码来了
$arr = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
$arr[] = $row;
$_SESSION['cart-checkout'] = $arr;
$quantity=$_SESSION['cart'][$id]['quantity'];
$sub_total=$price*$quantity;
echo "<div class='cart-row'>";
echo "<div class='col-md-8'>";
echo "<div class='product-name m-b-10px'><h4>{$name}</h4>
</div>";
echo $quantity>1 ? "<div>{$quantity} items</div>" : "<div>
{$quantity} item</div>";
echo "</div>";
echo "<div class='col-md-4'>";
echo "<h4>$" . number_format($price, 2, '.', ',') . "
</h4>";
echo "</div>";
echo "</div>";
$item_count += $quantity;
$total+=$sub_total;
}
答案 0 :(得分:2)
您在那儿。您正在循环内递增,但要获得总数,您需要在循环外打印。另外,您还需要在开始时声明变量total。
尝试一下:
$arr = array();
$total = 0; //declare variable
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
$arr[] = $row;
$_SESSION['cart-checkout'] = $arr;
$quantity=$_SESSION['cart'][$id]['quantity'];
$sub_total=$price*$quantity;
echo "<div class='cart-row'>";
echo "<div class='col-md-8'>";
echo "<div class='product-name m-b-10px'><h4>{$name}</h4>
</div>";
echo $quantity>1 ? "<div>{$quantity} items</div>" : "<div>
{$quantity} item</div>";
echo "</div>";
echo "<div class='col-md-4'>";
echo "<h4>$" . number_format($price, 2, '.', ',') . "
</h4>";
echo "</div>";
echo "</div>";
$item_count += $quantity;
$total+=$sub_total;//increment inside loop
}
echo $total;//print outside loop