购物车输出

时间:2012-03-16 13:18:54

标签: php mysql

我有一个在线商店。一个产品页面,允许用户查看产品并将其添加到购物篮中。通过单击“添加到购物篮”按钮将其添加到购物篮中。

当用户点击“添加到购物篮”时,脚本会将其重定向到购物篮页面并将产品添加到购物篮中。

我的问题是,如何在“basket.php”页面上打印篮子输出?如何将会话内容传递给要打印的变量?

谢谢。

数据库中的“products”表:

id int(11), name varchar(255), price int(11)

product.php

 ...

<form id="basket" name="basket" method="post" action="basket.php">
    <input type="hidden" name="p_id" value="<?php echo $id; ?>"/>
    <input type="submit" name="submit" value="Add to basket"/>
</form>

...

basket.php

<?php 
 //add product to cart with product ID passed from previous script 
    if (isset($_POST["p_id"]))
     { 
        $p_id = $_POST["p_id"];
        $q = mysql_query("SELECT * FROM products WHERE id='$p_id'"); 
        $is = mysql_fetch_row($q); $is = $is[0]; 

        $result = "";
    while($row = mysql_fetch_array($q)) {
        $name = $row["name"];
        $price = $row["price"];
        $info = $row["info"];
    }

    $result .= $name .= $price .= $info;


        //$_SESSION['p_id'] contains product IDs 
        //$_SESSION['counts'] contains item quantities 
        // ($_SESSION['counts'][$i] corresponds to $_SESSION['p_id'][$i])
        //$_SESSION['p_id'][$i] == 0 means $i-element is 'empty' (does not refer to any     product)


        if (!isset($_SESSION["p_id"])) 
        { 
            $_SESSION["p_id"] = array(); 
            $_SESSION["counts"] = array(); 
        } 
        //check for current product in visitor's shopping cart content 
        $i=0; 
        while ($i<count($_SESSION["p_id"]) && $_SESSION["p_id"][$i] != $_POST["p_id"])     $i++; 
        if ($i < count($_SESSION["p_id"])) //increase current product's item quantity 
        { 
            $_SESSION["counts"][$i]++;
        } 
        else //no such product in the cart - add it 
        { 
            $_SESSION["p_id"][] = $_POST["p_id"]; 
            $_SESSION["counts"][] = 1; 
        } 
    } 

?>



<div>

<?php echo $result ?>

</div>

1 个答案:

答案 0 :(得分:0)

按钮点击创建ajax请求,使用GET veriable todo ='add_to_basket'创建一个basket.php,你将在basket.php中处理

您添加产品按钮或链接的HTML

<a href="#" onclick="add_to_basket(<?=$YOUR_PRODUCT_ID?>)"></a>

您的产品数量,您将通过Jquery获得,只需输入带有ID的计数html选择器

<select id="count_<?=$YOUR_PRODUCT_ID?>"></select>



function add_to_basket(product_id){
var product = {};
product['prod_id'] = product_id;
//here you get count of current product
product['count'] = $("count_"+product_id).val();
$.ajax({
  type: "GET",
  url: "your_domain/basket.php?todo=add_to_basket",
  data: "product",
  success:function () {
  }
});
}
在你的basket.php上

你就像那样处理这个请求

if ($GET['todo'] == "add_to_basket"){
  // here you add your data(witch comes from ajax) to SESSION
  $_SESSION['basket'] [$GET['prod_id']] = $GET['count'];
  return true;
}

然后当用户点击购物篮图像时,您将其重定向到购物篮页面,您将在会话中显示所有产品

<?foreach ($_SESSION['basket'] as $item){?>
// here you get product info by product id from your database and product count from $_SESSION  print it to view , price wille be count*price

<?}?>