将会话数组中的购物车项目添加到mysql数据库

时间:2019-04-30 23:47:23

标签: php mysql arrays session

如何将购物车中的数据发送到mysql数据库中,此刻我可以将商品添加到购物车中并且可以清除,但是我也创建了checkout按钮,但无法弄清楚如何从购物车中获取数据到mysql数据库,我已经尝试了动作check_out,但是我这样做是完全错误的

这是我的action.php,它将购物车中的物品排列成阵列并添加或删除。

<?php
include('cart/database_connection.php');
//action.php

session_start();

if(isset($_POST["action"]))
{
    if($_POST["action"] == "add")
    {
        if(isset($_SESSION["shopping_cart"]))
        {
            $is_available = 0;
            foreach($_SESSION["shopping_cart"] as $keys => $values)
            {
                if($_SESSION["shopping_cart"][$keys]['product_id'] == $_POST["product_id"])
                {
                    $is_available++;
                    $_SESSION["shopping_cart"][$keys]['product_quantity'] = $_SESSION["shopping_cart"][$keys]['product_quantity'] + $_POST["product_quantity"];
                }
            }
            if($is_available == 0)
            {
                $item_array = array(
                    'product_id'               =>     $_POST["product_id"],  
                    'product_name'             =>     $_POST["product_name"],  
                    'product_price'            =>     $_POST["product_price"],  
                    'product_quantity'         =>     $_POST["product_quantity"]
                );
                $_SESSION["shopping_cart"][] = $item_array;
            }
        }
        else
        {
            $item_array = array(
                'product_id'               =>     $_POST["product_id"],  
                'product_name'             =>     $_POST["product_name"],  
                'product_price'            =>     $_POST["product_price"],  
                'product_quantity'         =>     $_POST["product_quantity"]
            );
            $_SESSION["shopping_cart"][] = $item_array;
        }
    }

    if($_POST["action"] == 'remove')
    {
        foreach($_SESSION["shopping_cart"] as $keys => $values)
        {
            if($values["product_id"] == $_POST["product_id"])
            {
                unset($_SESSION["shopping_cart"][$keys]);
            }
        }
    }
    if($_POST["action"] == 'empty')
    {
        unset($_SESSION["shopping_cart"]);
    }


    if($_POST["action"] == 'check_out')
    {
        if(isset($_SESSION["shopping_cart"]))
        {
            foreach($_SESSION["shopping_cart"] as $values)
        {
             $sql ="INSERT INTO orders (total, product_id)
                    values ('{$values['product_id']}','{$v['total']}')";
                    $statement = $connect->prepare($query);
                    $statement->execute();
        if ($statement) {
            $_SESSION['success'] = 'Information updated successfully';

            header("location: my_account.php");
            exit;
        } else {
            $_SESSION['errormsg'] = 'Someting is wrong in updating your Information, Please try again later.';
            header("location: my_account2.php");
            exit;
        }}
    }

}
?>

这是脚本,我正在使用该脚本调用index.php中的函数

<script>  
$(document).ready(function(){
    load_cart_data();

    function load_product()
    {
        $.ajax({
            url:"cart/fetch_item.php",
            method:"POST",
            success:function(data)
            {
                $('#display_item').html(data);
            }
        });
    }

    function load_cart_data()
    {
        $.ajax({
            url:"cart/fetch_cart.php",
            method:"POST",
            dataType:"json",
            success:function(data)
            {
                $('#cart_details').html(data.cart_details);
                $('.total_price').text(data.total_price);
                $('.badge').text(data.total_item);
            }
        });
    }

    $('#cart-popover').popover({
        html : true,
        container: 'body',
        content:function(){
            return $('#popover_content_wrapper').html();
        }
    });

    $(document).on('click', '.add_to_cart', function(){
        var product_id = $(this).attr("id");
        var product_name = $('#name'+product_id+'').val();
        var product_price = $('#price'+product_id+'').val();
        var product_quantity = $('#quantity'+product_id).val();
        var action = "add";
        if(product_quantity > 0)
        {
            $.ajax({
                url:"cart/action.php",
                method:"POST",
                data:{product_id:product_id, product_name:product_name, product_price:product_price, product_quantity:product_quantity, action:action},
                success:function(data)
                {
                    load_cart_data();
                    alert("Item has been Added into Cart");
                }
            });
        }
        else
        {
            alert("Please Enter Number of Quantity");
        }
    });

    $(document).on('click', '.delete', function(){
        var product_id = $(this).attr("id");
        var action = 'remove';
        if(confirm("Are you sure you want to remove this product?"))
        {
            $.ajax({
                url:"cart/action.php",
                method:"POST",
                data:{product_id:product_id, action:action},
                success:function()
                {
                    load_cart_data();
                    $('#cart-popover').popover('hide');
                    alert("Item has been removed from Cart");
                }
            })
        }
        else
        {
            return false;
        }
    });

    $(document).on('click', '#clear_cart', function(){
        var action = 'empty';
        $.ajax({
            url:"cart/action.php",
            method:"POST",
            data:{action:action},
            success:function()
            {
                load_cart_data();
                $('#cart-popover').popover('hide');
                alert("Your Cart has been clear");
            }
        });
    });

$(document).on('click', '#check_out_cart', function(){
        var action = 'empty';
        $.ajax({
            url:"cart/action.php",
            method:"POST",
            data:{action:action},
            success:function()
            {
                load_cart_data();
                $('#cart-popover').popover('hide');
                alert("Your Cart has been clear");
            }
        });
    });




});

</script>

databaseconnection.php

<?php

//database_connection.php

$connect = new PDO("mysql:host=localhost;dbname=foodsystem", "root", "");

?>

我已经检查了购物车会话,并且可以看到数组中的项目

Array
(
    [0] => Array
        (
            [product_id] => 1
            [product_name] => Chicken Burger
            [product_price] => 10
            [product_quantity] => 1
        )

    [1] => Array
        (
            [product_id] => 2
            [product_name] => Fish Burger
            [product_price] => 10
            [product_quantity] => 1
        )

    [2] => Array
        (
            [product_id] => 3
            [product_name] => Ham Burger
            [product_price] => 10
            [product_quantity] => 1
        )

1 个答案:

答案 0 :(得分:0)

您定义一个名为$sql的变量,然后运行一个名为$query的变量。

发生这类错误是因为首先将查询作为变量,然后将其执行基本上是有问题的。最好将查询定义为参数,这样您就不会“错过”:

$stmt = $connect->prepare("INSERT INTO orders (total, product_id) VALUES (:total, :product_id)");
$stmt->execute($v);

偶然发生错误查询或完全不执行查询的可能性为零。

这也通过使用占位符值来修复SQL injection bug,PDO太容易了,以至于没有理由不这样做。如果您将查询中的命名占位符与$v中的键进行匹配,它将自动使用正确的数据运行。