如何使用php存储登录用户的购物车会话

时间:2016-02-20 15:54:10

标签: php ajax session variables cart

您好我正在创建一个简单的Web应用程序,用户可以登录并购买食物。我使用过在线link to tutorial

的教程

实现此Web应用程序的排序方面, 现在我已经实现了一个用户系统,因此用户必须登录才能下订单。

我的问题是我注意到登录时会向多个用户显示相同的购物车信息,这是错误的。每个用户都应该根据他们可能添加的内容来拥有自己不同的购物车信息。 所以我想问我如何将购物车信息与登录用户或每个用户联系起来。

这是我的代码段

product.php

<head>
    <script>
function showEditBox(editobj,id) {
    $('#frmAdd').hide();
    $(editobj).prop('disabled','true');
    var currentMessage = $("#message_" + id + " .message-content").html();
    var editMarkUp = '<textarea rows="5" cols="80" id="txtmessage_'+id+'">'+currentMessage+'</textarea><button name="ok" onClick="callCrudAction(\'edit\','+id+')">Save</button><button name="cancel" onClick="cancelEdit(\''+currentMessage+'\','+id+')">Cancel</button>';
    $("#message_" + id + " .message-content").html(editMarkUp);
}
function cancelEdit(message,id) {
    $("#message_" + id + " .message-content").html(message);
    $('#frmAdd').show();
}
function cartAction(action,product_code) {
    var queryString = "";
    if(action != "") {
        switch(action) {
            case "add":
                queryString = 'action='+action+'&code='+ product_code+'&quantity='+$("#qty_"+product_code).val();
            break;
            case "remove":
                queryString = 'action='+action+'&code='+ product_code;
            break;
            case "empty":
                queryString = 'action='+action;
            break;
        }    
    }
    jQuery.ajax({
    url: "ajax_action.php",
    data:queryString,
    type: "POST",
    success:function(data){
        $("#cart-item").html(data);
        if(action != "") {
            switch(action) {
                case "add":
                    $("#add_"+product_code).hide();
                    $("#added_"+product_code).show();
                break;
                case "remove":
                    $("#add_"+product_code).show();
                    $("#added_"+product_code).hide();
                break;
                case "empty":
                    $(".btnAddAction").show();
                    $(".btnAdded").hide();
                break;
            }    
        }
    },

    error:function (){}
    });

}


    </script>
</head>
<body>
<div id="product-grid">
    <?php
    $product_array = $db_handle->runQuery("SELECT * FROM tblproduct ORDER BY id ASC");
    if (!empty($product_array)) { 
        foreach($product_array as $key=>$value){
    ?>
        <div class="product-item">
            <form id="frmCart">
<img width="100" src="<?php echo $product_array[$key]["image"]; ?>">
            <div><strong><?php echo $product_array[$key]["name"]; ?></strong></div>
            <div class="product-price"><?php echo "MUR".$product_array[$key]["price"]; ?></div>
            <div><input type="range" name="quantity" id="qty_<?php echo $product_array[$key]["code"]; ?>"  value="1" min="1" max="10">
            <?php
                $in_session = "0";
                if(!empty($_SESSION["cart_item"])) {
                    $session_code_array = array_keys($_SESSION["cart_item"]);
                    if(in_array($product_array[$key]["code"],$session_code_array)) {
                        $in_session = "1";
                    }
                }
            ?>

            <input data-theme="a" type="button" data-icon="cutlery"  value="Add to cart" class="btnAddAction cart-action" onClick = "cartAction('add','<?php echo $product_array[$key]["code"]; ?>');cartAction('add','<?php echo $product_array[$key]["code"]; ?>')"  />

            </div>
            </form>
        </div>
    <?php
            }
    }
    ?>
</div>
</div><div class="clear-float"></div>
<div id="shopping-cart">


</div>
<script>
$(document).ready(function () {
    cartAction('','');
})
</script> 





</div>




</div>
</body>

和我的ajax_action.php

<?php
session_start();
require_once("dbcontroller.php");
$db_handle = new DBController();

if(!empty($_POST["action"])) {
switch($_POST["action"]) {
    case "add":
        if(!empty($_POST["quantity"])) {
            $productByCode = $db_handle->runQuery("SELECT * FROM tblproduct WHERE code='" . $_POST["code"] . "'");
            $itemArray = array($productByCode[0]["code"]=>array('name'=>$productByCode[0]["name"], 'code'=>$productByCode[0]["code"], 'quantity'=>$_POST["quantity"], 'price'=>$productByCode[0]["price"]));

            if(!empty($_SESSION["cart_item"])) {
                if(in_array($productByCode[0]["code"],$_SESSION["cart_item"])) {
                    foreach($_SESSION["cart_item"] as $k => $v) {
                            if($productByCode[0]["code"] == $k)
                                $_SESSION["cart_item"][$k]["quantity"] = $_POST["quantity"];
                    }
                } else {
                    $_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray);
                }
            } else {
                $_SESSION["cart_item"] = $itemArray;
            }
        }
    break;
    case "remove":
        if(!empty($_SESSION["cart_item"])) {
            foreach($_SESSION["cart_item"] as $k => $v) {
                    if($_POST["code"] == $k)
                        unset($_SESSION["cart_item"][$k]);
                    if(empty($_SESSION["cart_item"]))
                        unset($_SESSION["cart_item"]);
            }
        }
    break;
    case "empty":
        unset($_SESSION["cart_item"]);
    break;      
}
}
?>
<?php
if(isset($_SESSION["cart_item"])){
    $item_total = 0;
?>  


<?php       
    foreach ($_SESSION["cart_item"] as $item){
        ?>
                <img width="50" src="<?php 
                $img = $item["name"];
                $sql = "select * FROM tblproduct where name = '$img'";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
    echo $row['image'];
}
?>" /><input type="hidden" name="itemname[]" id="text-basic" value="<?php echo $item["name"]; ?>"><input type="hidden" name="itemprice[]" id="text-basic" value="<?php echo $item["price"]; ?>"><strong><?php echo $item["name"]; ?></strong><br />


                <?php echo "MUR".$item["price"]; ?> x <?php echo $item["quantity"]; ?>
                <a style="color:#F30" href="#"  onClick="cartAction('remove','<?php echo $item["code"]; ?>')" class="btnRemoveAction cart-action">Remove Item</a><br /><br />

                <?php
        $item_total += ($item["price"]*$item["quantity"]);
        }
        ?>

<br /><br /><strong>Total:</strong> <?php echo "MUR".$item_total; ?><input type="hidden" name="amount" id="text-basic" value="<?php echo "N".$item_total; ?>">      
  <?php
}
?>

我试图将$_SESSION["cart_item"]更改为总是会更改$_SESSION["MM_Username"]的内容,我的想法是它可能会根据登录的人创建购物车变量名称,但这种方法似乎没有顺利, 有人可以帮助

0 个答案:

没有答案