2013-04-12 217 views
1
<?php 

session_start(); 
print '<h1>Your Shopping Cart:</h1>'; 
print '<h4>The Product ID: '.$_SESSION['id'].' </h4>'; 
print '<h4>The Quantity: '.$_SESSION['quantity'].' </h4>'; 

$dbc = mysql_connect('127.0.0.1', 'root', ''); 
mysql_select_db('product', $dbc); 

$query = "SELECT * FROM prod WHERE id='".$_SESSION['id']."'"; 



if ($r = mysql_query($query, $dbc)) { 

while ($row = mysql_fetch_array($r)) { 
print "<p><b>Product Name: {$row['name']}<br /> 
      The Price: {$row['price']}<br /> 
      Shipping Cost: {$row['shipping']}<br /> 



</p><hr />\n"; 
}} 
?> 

此代碼爲購物車與會議,但問題是,它只保留一個產品。購物車會話php

舉例來說,如果您購買產品A和車產品B刪除B,則添加產品 請幫我 我想添加一個以上的產品和印製在屏幕##

回答

2

添加另一個上水平到您的購物車:

$_SESSION['cart'][$productID]['quantity']; 
       ^^^^^^^^^^^^^ 

所以你保持每個產品的數據。現在,您正在使用一個單一的級別,隨着新產品的添加,您將不斷覆蓋。

2

問好PHP數組:http://www.php.net/manual/en/book.array.php :)
基本上代替:

$_SESSION['id'] = 1234; 

你會想:

$_SESSION['products'][] = array('id'=>1234, 'quantity'=>10); 

然後你會遍歷$ _SESSION [ '產品']像

foreach($_SESSION['products'] AS $product){ 
    echo $product['id']; 
} 
0

你應該保持你的c藝術在單個會話變量$_SESSION['cart']。當您添加新產品時,您可以使用此功能,

$_SESSION['cart'] = array();   //initialize once 
array_push($_SESSION['cart'], array("id" => $id, "quantity" => $q)); 
print_r($_SESSION['cart']); 

這樣,您可以在購物車中放置多個產品。

對於特定的框架CodeIgniter,有一個提供購物車功能的類。檢查this了。

+1

不是一個好的設計。如果產品已經在購物車中,那麼您將創建重複的購物車條目。通常應該通過產品的關鍵字來對購物車進行索引,以便將產品的購物車信息集中到一個地方。 –

0
$_SESSION['cart'] = array(); 
$_SESSION['cart']['1'] = 2;//add product A,id=1,quality=2 
$_SESSION['cart']['2'] = 3;//add product B,id=2,quality=3 

//get all items 
foreach($_SESSION['cart'] as $item) 
{ 
    print_r($item); 
}