Prin Puyakul Prin Puyakul -4 years ago 69
MySQL Question

Update cart with PHP+ MYSQL (PDO connection)

I'm current building up an online shopping for my assignment. I have everything pretty much up and running, but I would like to improve my shopping cart functional.
Now it can only add one item to cart and when I try to add the same item it will say item already exists, I would like to ask if anyone know how do I modify this code from this original to add more into the cart instead of saying the item already exists. Thank you so much in advance and really appreciate all comments ^^"
PS. below is my code.

> <?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; ?>

Answer Source

I personally would make the id value the key name, it would be easier to retrieve and edit. I would also make a couple classes to help make your script more human-readable. See the addToCart() method to show how to add to the cart where the item is already set:

# 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';
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download