【发布时间】:2020-08-15 23:02:00
【问题描述】:
我正在我的网站中创建一个添加到购物车的系统。
如果购物车中没有商品,则变量$cart 设置为NULL。
当我尝试回显购物车中的商品数量时,这会导致以下错误:count(): Parameter must be an array or an object that implements Countable。
这是我的 php 代码:
<?php
if ((isset($_SESSION['active_user_type']) && $_SESSION['active_user_type'] == "consumer") || !isset($_SESSION['active_user'])) {
?>
<div class="shopping_cart">
<div class="cart_title">
<a href="view_cart.php">Shopping cart</a>
</div>
<?php
$total = 0;
if(isset($_SESSION['cart'])) {
$cart = $_SESSION['cart'];
for ($i=0; $i<count($cart); $i++) {
$item_id = $cart[$i][0];
$query = "SELECT * FROM items WHERE id=$item_id";
$result = $db->query($query);
if ($row = $result->fetch()) {
$price = ($row['price']*$cart[$i][1]) + $row['shipping_price'];
}
$total += $price;
}
} else {
$cart = NULL;
}
?>
<div class="cart_details">
// the error seems to be from the line below:
<?php echo count($cart); ?><br />
<span class="border_cart"></span> Total:
<span class="price">
<?php echo "BD " . number_format((float)$total,3,'.',''); ?>
</span>
</div>
<div class="cart_icon">
<a href="checkout.php" title="Checkout">
<img src="images/shoppingcart.png" alt="" width="48" height="48" border="0" />
</a>
</div>
</div>
<?php
}
?>
【问题讨论】: