【问题标题】:PHP Add to cart session errorPHP 添加到购物车会话错误
【发布时间】:2014-12-14 18:30:07
【问题描述】:

我正在测试这个简单的购物车代码,但由于某种原因它似乎不起作用。我创建了 3 页,第 1 页包含:

<a href="add-to-cart.php?id=1">Item 1</a><br><br>
<a href="add-to-cart.php?id=2">Item 2</a><br><br>
<a href="add-to-cart.php?id=3">Item 3</a><br><br>

在第二个(add-to-cart.php)页面:

<?php
session_start();

if(empty($_session['cart'])){
$_session['cart'] = array();
}

array_push($_session['cart'], $_GET['id']);
?>
<br><br>
Product is succesfully added to cart.
<a href="cart.php">View Cart Items</a>

最后,在第三个(cart.php)页面:

<?php 
session_start();

var_dump($_session['cart']);
?>

而不是数组,我得到这个错误:

注意:未定义变量:第 4 行 C:\xampp\htdocs\projects\add_to_cart\independent\compare.php 中的 _session

【问题讨论】:

  • 文件在哪里:compare.php在这个文件中是错误的?!
  • 哎呀,抱歉 rizier123 它的通知:未定义的变量:C:\xampp\htdocs\projects\add_to_cart\independent\cart.php 中的 _session 第 4 行
  • 那我的回答应该对你有用!

标签: php session


【解决方案1】:

你必须用大写字母写会话,例如:

$_SESSION["cart"] 

而不是:

$_session["cart"]  //if you write it like this it's a normal array

所以你的代码应该是这样的:

添加到购物车.php:

<?php
session_start();

if(empty($_SESSION['cart'])){
$_SESSION['cart'] = array();
}

array_push($_SESSION['cart'], $_GET['id']);
?>
<br><br>
Product is succesfully added to cart.
<a href="cart.php">View Cart Items</a>

cart.php:

<?php 

    session_start();
    var_dump($_SESSION['cart']);

?>

欲了解更多信息,请参阅:http://php.net/manual/en/reserved.variables.session.php

【讨论】:

    【解决方案2】:

    使用大写的$_SESSION。 PHP 中的变量名区分大小写。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多