使用 PHP+ MYSQL 更新购物车(PDO 连接)

Update cart with PHP+ MYSQL (PDO connection)

我目前正在为我的作业建立在线购物。我的一切都差不多 运行,但我想改进我的购物车功能。 现在它只能将一件商品添加到购物车,当我尝试添加相同的商品时,它会说商品已经存在,我想问问是否有人知道如何修改此原始代码以将更多商品添加到购物车而不是说该项目已经存在。提前非常感谢您,非常感谢所有评论 ^^” PS。下面是我的代码。

<?php require '../ppuyakul/php/userIndex.php'; require
'../ppuyakul/php/db_conn.php';

$msg ='PLEASE SELECT ITEM';

if(isset($_POST["add_to_cart"])):  
    if(isset($_SESSION["shopping_cart"])):  
         $item_array_id = array_column($_SESSION["shopping_cart"], "item_id");  
         if(!in_array($_GET["id"], $item_array_id)):             
              $count = count($_SESSION["shopping_cart"]);  
              $item_array = array(  
                   'item_id'=>$_GET["id"],  
                   'item_name'=>$_POST["hidden_name"],  
                   'item_price'=>$_POST["hidden_price"],  
                   'item_quantity'=>$_POST["quantity"]
              );  
              $_SESSION["shopping_cart"][$count] = $item_array;
              $msg = 'PRODUCT ADDED';    
         else:  
              $msg = 'PRODUCT ALREADY EXISTS';

         endif;  
    else:  
         $item_array = array(  
              'item_id'=>$_GET["id"],  
              'item_name'=>$_POST["hidden_name"],  
              'item_price'=>$_POST["hidden_price"],  
              'item_quantity'=>$_POST["quantity"]  
         );  
         $_SESSION["shopping_cart"][0] = $item_array;  
    endif;
endif;  

if(isset($_GET["action"])): 
    if($_GET["action"] == "delete"):          
         foreach($_SESSION["shopping_cart"] as $keys => $values):              
              if($values["item_id"] == $_GET["id"]):                  
                   unset($_SESSION["shopping_cart"][$keys]);  
                   $msg = 'PRODUCT REMOVED';  
              endif; 
         endforeach;  
    endif;
endif;    ?>

我个人会将 id 值作为键名,这样更容易检索和编辑。我还会制作一些 类 来帮助您的脚本更易于阅读。请参阅 addToCart() 方法以显示如何添加到已设置商品的购物车:

# I would create a general class to help fetch some basic elements
class App   
    {
        # Easily extract $_POST array and values
        public  function getPost($key=false,$default=false)
            {
                if(!empty($key))
                    return (isset($_POST[$key]))? $_POST[$key] : $default;

                return $_POST;
            }
        # Easily extract $_GET array and values
        public  function getGet($key=false,$default=false)
            {
                if(!empty($key))
                    return (isset($_GET[$key]))? $_GET[$key] : $default;

                return $_GET;
            }
        # Easily extract $_SESSION array and values
        public  function getSession($key=false,$default=false)
            {
                if(!empty($key))
                    return (isset($_SESSION[$key]))? $_SESSION[$key] : $default;

                return $_SESSION;
            }
    }
# This is your shopping cart class that extends the basic class
class ShoppingCart extends App
    {
        # Fetches an item in cart, if item is actually in the cart
        public  function getItem($id)
            {
                return (isset($_SESSION['shopping_cart'][$id]))? $_SESSION['shopping_cart'][$id] : false;
            }
        # Adds to the cart
        public  function addToCart($id,$name,$price,$qty=1)
            {
                if(isset($_SESSION['shopping_cart'][$id]))
                    $_SESSION['shopping_cart'][$id]['item_quantity']    +=  $qty;
                else {
                    $_SESSION['shopping_cart'][$id]['item_name']        =   $name;
                    $_SESSION['shopping_cart'][$id]['item_price']       =   $price;
                    $_SESSION['shopping_cart'][$id]['item_quantity']    =   $qty;
                }
            }
        # Removes from the cart
        public  function removeFromCart($id)
            {
                if(isset($_SESSION['shopping_cart'][$id]))
                    unset($_SESSION['shopping_cart'][$id]);
            }
        # Checks if the action is set to add
        public  function isAdding()
            {
                return (isset($_POST["add_to_cart"]));
            }
        # Checks if the action is set to remove
        public  function isRemoving()
            {
                return ($this->getGet("action") == 'delete');
            }
        # Just start the cart if not already started
        public  function startCart()
            {
                if(!isset($_SESSION['shopping_cart']))
                    $_SESSION['shopping_cart']  =   array();
            }
    }
# Messaging
$msg    =   '';
# Create the cart instance
$Cart   =   new ShoppingCart();
# If adding to cart
if($Cart->isAdding()) {
    # Start the cart array
    $Cart->startCart();
    # Add to the cart
    $Cart->addToCart(
        $Cart->getGet("id"),
        $Cart->getPost("hidden_name"),
        $Cart->getPost("hidden_price"),
        $Cart->getPost("quantity",1)
    );
    # Set messaging
    $msg = 'PRODUCT ADDED';
}
# Check if the action is deleting
elseif($Cart->isRemoving()) {
    # Remove the id from the cart
    $Cart->removeFromCart($Cart->getGet("id"));  
    # Create messaging
    $msg = 'PRODUCT REMOVED';
}

而不是使用 $count 作为购物车的数组键。使用产品 ID。我会以这种方式重做您的代码:

if (isset($_POST["add_to_cart"])):
    $new_item_id = $_GET["id"];
    $item_array = [
        'item_id' => $new_item_id,
        'item_name' => $_POST["hidden_name"],
        'item_price' => $_POST["hidden_price"],
        'item_quantity' => $_POST["quantity"]
    ];
    if (isset($_SESSION["shopping_cart"]) && isset($_SESSION["shopping_cart"][$new_item_id])):
        $_SESSION["shopping_cart"][$new_item_id]['item_quantity'] += $item_array['item_quantity'];
        $msg = 'PRODUCT ALREADY IN CART, QTY INCREASED';
    else:
        $_SESSION["shopping_cart"][$new_item_id] = $item_array;
        $msg = 'PRODUCT ADDED';
    endif;
endif;

if (isset($_GET["action"]) && $_GET["action"] == "delete"):
    foreach ($_SESSION["shopping_cart"] as $item_id => $item):
        if ($item_id == $_GET["id"]):
            unset($_SESSION["shopping_cart"][$item_id]);
            $msg = 'PRODUCT REMOVED';
        endif;
    endforeach;
endif;

最终,当您掌握了所有基础知识后,将其转换为提到的 OOP。