【问题标题】:shopping cart Session php购物车会话 php
【发布时间】:2013-04-12 20:04:14
【问题描述】:
    <?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";
 }}
?>

此代码用于带有 Session 的购物车,但问题是它只保留一个产品。

例如,如果您购买产品 A,然后在购物车中删除产品 B,然后添加产品 A 请帮我 我想添加多个产品并打印在屏幕上##

【问题讨论】:

    标签: php shopping


    【解决方案1】:

    将另一个级别添加到您的购物车:

    $_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['products']

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

      【讨论】:

        【解决方案3】:

        您应该在单个会话变量$_SESSION['cart'] 中维护您的购物车。添加新产品时,您可以使用它,

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

        这样,您可以在购物车中拥有多个产品。

        对于特定的框架,CodeIgniter,有一个提供购物车功能的类。签出this

        【讨论】:

        • 不是一个好的设计。如果产品已经在购物车中,您将创建重复的购物车条目。购物车通常应该由产品的键索引,因此您可以将产品的购物车信息集中在一个地方。
        【解决方案4】:
        $_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);
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2023-03-27
          • 1970-01-01
          • 1970-01-01
          • 2011-08-18
          • 1970-01-01
          • 1970-01-01
          • 2020-03-17
          相关资源
          最近更新 更多