【发布时间】:2017-10-23 00:48:35
【问题描述】:
我希望有人可以帮助我。我不明白如何使用会话将产品信息从我的产品页面传递到我的购物车页面。我已经看到很多教程展示了如何在同一页面中使用它,但是没有什么可以理解的将它从一个页面传递到另一个页面。谢谢您的帮助!
这是我的带有数据文件连接的产品页面。
<?php
session_start();
$data = file('products.dat');
foreach ($data as $line) {
$products = explode(",", $line);
$id = $products[0];
$product = $products[1];
$description = $products[2];
$price = $products[3];
$image = $products[4];
$_SESSION['cart'] = array($id, $product, $price);
?>
<div class="product">
<?php print "<image class=\"product_image\" src=\"img/$image\">" ?><br>
<?php print $id; ?><br>
<?php print $title; ?><br>
<?php print $description; ?><br>
<?php print $price; ?>
<form method="get" action="viewcart.php?action=addcart">
<div>
<input type="hidden" name="product" value="<?php print $product?>" />
<input type="hidden" name="price" value="<?php print $price?>" />
<button type="submit">Add To Cart</button>
</div> <br>
</form>
</div>
<?php }; ?>
还有我的购物车页面。
<?php
session_start();
?>
<table border="1" cellspacing="0" cellpadding="10" width="100%">
<tr>
<th class="left">Product</th>
<th>Quantity</th>
<th>Price</th>
</tr>
<tr>
<td class="left"><?php print $_SESSION['cart'][1]; ?></td>
<td class="center">1</td>
<td class="center"><?php print $_SESSION['cart'][2]; ?></td>
</tr>
</table>
编辑:我在每个页面上都添加了一个session_start(),并编辑了我的产品页面,以便在我的初始 foreach 循环中有一个$_SESSION['cart'],在测试时它将打印出每个项目的正确信息。新问题是,当我向购物车添加东西时,GET 通过 URL 发送正确的信息,但只会显示 products 数组中的最后一项。这里有什么建议吗?
【问题讨论】:
-
作为一个简短的概述,
$_SESSION['cart']可以包含一系列购物车项目,每个项目都应该有一个产品 ID、数量,以及客户在提交它时看到的潜在价格购物车,或对当时定价 ID 的引用。session_start()应该存在于您需要使用$_SESSION的任何页面上。 -
当您加载购物车页面时,您将使用来自
$_SESSION['cart']的产品 ID 和数量与数据库中显示的内容保持一致。 -
谢谢@Scuzzy。我更新了我的代码并遇到了一个新问题,它只显示 products 数组中的最后一项。我已经更新了上面的代码以显示我做了什么。
-
这是因为您正在获取产品数据库,并且对于每个循环,您都尝试设置
$_SESSION['cart'] = array($id, $product, $price);,这意味着无论最后完成什么,都已设置。我没有看到您的“添加到购物车”逻辑,您所做的只是将 file('products.dat') 读入 $_SESSION['cart']