2013-04-12 218 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); 
}