[英]Shopping Cart $_SESSION Problem
我正在使用基本的購物車。 但是,似乎$ _SESSION變量未正確存儲或訪問。 例如,如果您前往這里 ,它將顯示商品名稱。 但是在刷新沒有任何$ _GET變量的cart.php時,它什么也不返回。 我究竟做錯了什么?
<?php
include "tickets/config.php";
if (isset ($_GET['action']) && isset($_GET['item'])) {
$cart = new Cart($_GET['item']);
if ($_GET['action'] == "addItem") {
$cart->addItem();
$cart->get_items_code();
$cart->populate();
}
if($_GET['action'] == "removeItem") {
$cart->removeItem();
$cart->get_items_code();
$cart->populate();
}
$cart->postAllItems();
}
else {
$cart = new Cart(null);
$cart->get_items_code();
$cart->populate();
$cart->postAllItems();
}
class Cart {
protected $all_items = array();
protected $request_item;
protected $content;
protected $item_obj;
public function __construct($request_item) {
$this->request_item = $request_item;
if ($this->request_item)
$this->item_obj = new Item($this->request_item);
$this->all_items = $this->getAllItems();
}
public function getAllItems() {
if ($_SESSION['cart'])
$request = $_SESSION['cart'];
else
$request = array();
return $request;
}
public function postAllItems() {
$_SESSION['cart'] = $this->all_items;
}
public function addItem () {
array_push($this->all_items, $this->item_obj);
}
public function removeItem() {
unset($this->all_items[$this->item_obj->get_item()]);
}
public function get_items_code() {
//for($i = 0; $this->all_items[$i]; $i++) {
foreach($this->all_items as $item) {
$name = $item->get_name();
$this->content .= <<<HTML
<div class="item">
$name
</div>
HTML;
}
}
public function populate() {
echo <<<HTML
<div id="list">
$this->content
<div>
HTML;
}
}
class Item {
protected $id;
protected $name;
protected $price;
protected $desc;
protected $colors;
protected $sizes;
protected $pic_url;
protected $all_info;
public function __construct($id) {
$this->id = $id;
$this->get_item_info();
}
public function get_item() {
return ($this);
}
public function get_name() {
return $this->name;
}
protected function get_item_info() {
$sql = "SELECT * FROM catalog WHERE id = ".$this->id;
$this->all_info = mysql_query($sql);
$this->all_info = mysql_fetch_array($this->all_info);
$this->name = $this->all_info['name'];
$this->price = $this->all_info['price'];
$this->desc = $this->all_info['description'];
$this->colors = $this->all_info['colors'];
$this->sizes = $this->all_info['sizes'];
$this->pic_url = $this->all_info['picture'];
}
}
?>
您需要使用頁面頂部的session_start()
-函數初始化會話(在修改或讀取會話內容之前)。
您的代碼看起來不錯,但是您必須在修改會話或從會話讀取的每個頁面上調用session_start()。 只需將其放在頁面頂部即可。
session_start();
最近,我也遇到了$ _SESSION變量在頁面重定向后自行維護的問題,這可能是您的問題。
從http://www.example.com重定向到http://example.com重定向后,會話變量將無法生存。 因此,您可以使用具有相對路徑或絕對路徑的重定向,但不要使用站點名稱:
采用
header('Location: /new_page.php');
相對於
header('Location: http://www.exmple.com/new_page.php')
也許這里不適用,但確實使我絆倒了很多。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.