我正在使用php中的第一个购物车。我有一个php文件来添加项目到购物车会话。 addcart.php
<?php
include 'dbconnect.php';
session_start();
$id= $_GET['id'];
if(!is_null($id)){
if(isset($_SESSION['cart']) && count($_SESSION['cart']) > 0){
// increment product quantity if already exists
// or create a new one
add_or_increment_product_to_cart($id, $_SESSION['cart']);
} else {
// initialize cart
// add the first product
$_SESSION['cart'] = array();
array_push($_SESSION['cart'], (object) array('id' => $id, 'quantity' => 1));
}
}
function add_or_increment_product_to_cart($id, $cart){
foreach ($cart as $key => $product) {
if($id == $product->id){
$product->quantity++;
return;
}
}
array_push($_SESSION['cart'], (object) array('id' => $id, 'quantity' => $product));
}
header('location:cart.php');
?>
我有一个php页面来显示购物车会话中的所有商品。如果我只是将一个项目添加到购物车中,它可以正常工作。
cart.php
<?php
$page_title = "Cart";
include_once ('header.html'); //include session_start() and others things
include ('dbconnect.php');
if($_SESSION['login']==null)
{
header ("location:login.php");
}
?>
<div id="content">
<table border="1">
<form action="update_cart.php" method="post">
<?php
$total_price=0;
if(isset($_SESSION['cart']) ? $_SESSION['cart'] : null)
{
echo "<tr>
<th></th>
<th>Product</th>
<th>Price</th>
<th>Quantity</th>
</tr>";
foreach ($_SESSION['cart'] as $key => $product) {
$the_query = "SELECT * FROM products WHERE id=" . $product->id." LIMIT 1";
$the_product = $db->query($the_query) or die('Query failed: ' . mysql_error());
$the_product->execute();
$the_product->setFetchMode(PDO::FETCH_OBJ);
while ($row = $the_product->fetch()){
echo "<tr><td>";
echo "<img src='".$row->image_url_small."' /></a></td>";
echo "<td><strong>".$row->name."</strong></td><td><em>$".$row->price."</em>";
echo '</td>';
echo '<td><input type="text" name="'.$row->id.'" class="override" value="'.$product->quantity.'"/></td>';
//echo '<td><a href="update_cart.php?id='.$row->id.'&quantity='.$product->quantity.'">Update</a></td>';
echo '<td><a href="do_deletecart.php?id='.$row->id.'">Delete item </a></td></tr>';
$total_price = $total_price + $row->price*$product->quantity;
}}
echo "<tr><td colspan='2'></td></tr>";
echo "<tr><td style='text-align:center;font-size:40px;'>$</td><td><strong>Total</strong><br /><em>$".$total_price."</em></td></tr>";
$_SESSION['total']=$total_price;
}
else {
echo "Your cart is empty.";
}
?>
<tr><td>
<!----<input type = "submit" value="Checkout"/></td>----->
<td><input type = "submit" value="Update"/></td></tr>
</form>
</table>
<br /><a href="empty_cart.php">Empty Cart</a> <a href="products.php">Show products</a><br /><br />
</div>
<?php
include_once ('footer.html');
?>
修复此错误的任何建议“捕获致命错误:类stdClass的对象无法在第37行的/home/s3393354/public_html/Assignment2/cart.php中转换为字符串”。
echo '<td><input type="text" name="'.$row->id.'" class="override" value="'.$product->quantity.'"/></td>';
提前致谢。
答案 0 :(得分:0)
在cart.php
中,顶部没有session_start();
。把它放在最上面
<?php
session_start();