目前,我有一個購物車,將添加一個項目的購物車會話。如果另一個相同的物品被添加到購物車中,則會顯示重複的物品,每個物品的數量爲1.將相同商品添加到購物車時增加數量?
我需要爲代碼添加/更改以更新現有物料的數量?而不是添加重複的項目。
add_to_cart.php
session_start();
include 'cart.php';
$item_id = $_POST['item_id'];
$qty = $_POST['qty'];
$counter = $_SESSION['counter'];
$cart = new Cart();
if ($counter>0)
{
$cart = unserialize($_SESSION['cart']);
}
else
{
$_SESSION['counter'] = 0;
$_SESSION['cart'] = "";
}
if (($item_id == "")or ($qty < 1))
{
header("Location: products.php");
}
else
{
require_once('conn_db.php');
$query = "SELECT item_name, price FROM products WHERE (item_id=$item_id)";
$result = mysql_query($query) or die("Database Error");
if(mysql_num_rows($result) == 1)
{
$price = mysql_result($result, 0,"price");
$item_name = mysql_result($result, 0, "item_name");
$new_item = new Item($item_id, $item_name, $qty, $price);
$cart->add_item($new_item);
$_SESSION['counter'] = $counter+1;
$_SESSION['cart'] = serialize($cart);
header("Location: products.php");
mysql_close();
}
else
{
header("Location: products.php");
}
}
cart.php
class Item {
var $item_id;
var $item_name;
var $qty;
var $price;
var $deleted = false;
function get_item_cost() {
return $this->qty * $this->price;
}
function delete_item() {
$this->deleted = true;
}
function Item($item_id, $item_name, $qty, $price) {
$this->item_id = $item_id;
$this->item_name = $item_name;
$this->qty = $qty;
$this->price = $price;
}
function get_item_id() {
return $this->item_id;
}
function get_item_name() {
return $this->item_name;
}
function get_qty() {
return $this->qty;
}
function get_price() {
return $this->price;
}
}
class Cart {
var $items;
var $depth;
function Cart() {
$this->items = array();
$this->depth = 0;
}
function add_item($item) {
$this->items[$this->depth] = $item;
$this->depth++;
}
function delete_item($item_no) {
$this->items[$item_no]->delete_item();
}
function get_depth() {
return $this->depth;
}
function get_item($item_no) {
return $this->items[$item_no];
}
}
創建
update_quantity()
你往前走了建立購物車,[閱讀此](http://xkcd.com/327/),那麼絕對不要試試這個'$ _POST ['item_id'] ='1); DROP TABLE products;('',然後[閱讀此](http://php.net/manual/en/function.mysql-real-escape-string.php),然後看看頁面頂部的大紅色警告框,然後[讀這個](http://www.php.net/manual/en/book.mysqli.php)。 – MLeFevre我知道,我很懶。它不會在現實世界中使用。只是一個學校的任務。 – BobSacamano