我正在做我的家庭作业。我有一个购物车会话,我可以根据产品 ID 获取 mySql 数据库中的属性。
<?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;
$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()){
$total_price = $total_price + $row->price*$product->quantity;
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" id="'.$row->id.'" class="override" value="'.$product->quantity.'"/></td>';
echo '<td><a href="do_deletecart.php?id="'.$row->id.'">Delete item </a></td></tr>';
}}
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>";
}
else {
echo "Your cart is empty.";
}
?>
更新我可以将 id 传递给 do_deletecart.php。但现在我可以从购物车 do_deletecart.php 中删除产品
<?php
session_start();
$product = $_GET['id'];
foreach($_SESSION['cart'] as $key=>$value) {
if($product == $value)
{
unset($_SESSION['cart'][$key]);
break;
} }
header("location:cart.php");
?>