我正在尝试将从SQL数据库中检索到的数据传递给$_SESSION
数组,以便将购物车显示给用户。我认为信息实际上并没有传递出去,该程序最终显示出来,但是却给了我空白的字段。作为参考,我正在尝试通过多个PHP文件传递数据。此外,一旦信息传递完毕,我不确定如何循环说$ _SESSION数组用户添加多个项目。
我不确定问题是通过我的include()
和我的index
,还是我的form action
在product_list
中。但是在某个地方,要么数据没有通过,要么以我认为的方式行不通。
这是我product_list
中最初发送数据的代码
foreach ($products as $product) : ?>
<tr>
<td><?php echo $product['productID']; ?></td>
<td><?php echo $product['productName']; ?></td>
<td class="right"><?php echo $product['price']; ?></td>
<td><form action="../Cart/index.php" method="post">
<input type="hidden" name="action"
value="add_product">
<input type="hidden" name="product_name"
value="<?php echo $product['productName'];?>">
<input type="hidden" name="product_price"
value ="<?php echo $product['price'];?>">
<input type="submit" value="Add to Cart">
<?php endforeach;
这是我的index
中包含购物车的代码
if ($action == 'add_product')
{
include('../Cart/index.php');
}
这是我在购物车路径中的索引中的代码
$action = 'add_to_cart';
if(!isset($_SESSION['cart']))
{
$_SESSION['cart'] = array();
}
if($action == 'add_to_cart')
{
$cart_product_name = filter_input(INPUT_GET, 'product_name');
$cart_product_price = filter_input(INPUT_GET, 'product_price', FILTER_VALIDATE_FLOAT);
$product = array('price' => $cart_product_price, 'name' => $cart_product_name);
$_SESSION['cart'][] = $product;
include('cart_view.php');
}
这是$_SESSION
数组应显示的位置
<main>
<h1>Your Cart</h1>
<link rel='stylesheet' type="text/css" href="main.css">
<?php
print_r($_SESSION['cart'][0]);
?>
实际显示的是这个Array ( [price] => [name] => )
我看到的第一个问题是您的输入名称不正确。当前输入的每个产品名称都是name =“ product_name”,同样是product_price。您需要将它们作为数组传递,或者每个传递都有自己唯一的键。否则,您将获得一个product_name和product_price的单个发布值-形式为带有这些名称的最后输入是任何形式。
您可以通过执行name =“ product_name []将它们作为数组传递,然后您的帖子将包含所有这些值的数组,并按照它们在表单中出现的顺序排列。
接下来,您说您的输出当前是Array([price] => [name] =>)。这向我表明您的会话实际上正在运行,因为您在该数组中有键。因此,实际上设置会话不是问题。因此,然后返回到设置会话的位置,并看到您正在filter_input参数中使用INPUT_GET,但是您正在接收POST值。您的参数不应为INPUT_GET,而应为INPUT_POST。
一旦清除所有内容,您仍然会遇到问题,因为product_name和product_price的输入将是具有多个值的数组。您需要遍历它们以组装设置为会话的最终数组。我将留给您探索,因为这看起来与您当前在add_to_cart动作中进行的操作大不相同。