使用$_SESSION和array_push的购物车;我似乎不记得购物车上的商品了


Shopping cart using $_SESSION and array_push doesn't seem to remember cart items

会话存储阵列似乎只记住一个键值对。当我按下浏览器中的后退按钮时,数组似乎是空的。我做错了什么?这是代码:谢谢你的帮助

<?php
if( !isset( $_SESSION ) ) {
    session_start();
       $_SESSION['cart']=array();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Shoppy</title>
</head>
<body>
<div><a href="index.php">back to store</a></div>
			<?php include 'products.inc.php'; ?>
			<?php $p=$_GET["product"] ?>
			<span><?php echo $products[$p]['name']; ?> </span><?php echo $products[$p]['price']; ?> €
			<div>
				<img src="<?php echo $products[$p]['picture']; ?>" alt="">
			</div>
			
	
	
	<form action="" method="POST">
		<input type="hidden" name="form" value=<?php echo $p ?>>
		<button type="submit">buy</button>
	</form>
	<?php if (!empty ($_POST) && isset($_POST))
{
	array_push($_SESSION['cart'], $_POST['form']);
	
	} ?>
	<?php include 'cart.inc.php'; ?>
</body>
</html>

更改

if( !isset( $_SESSION ) ) {
    session_start();
       $_SESSION['cart']=array();
}

session_start();
if( !isset($_SESSION['cart']) ) {
       $_SESSION['cart']=array();
}

在尝试对会话执行任何操作之前,您需要调用session_start()。此外,在检查是否已设置时,请检查会话变量(即isset($_SESSION['someindex']),而不是会话本身(即isset($_SESSION))。