DEV Community

David Kanekanian
David Kanekanian

Posted on

E5 - Temporary Shopping Cart

The cart is a tricky process requiring many steps.
Jump to section:

Explanation of Shopping Cart

The cart is a temporary collection of items where the user can add/edit/remove items before they confirm their order. It should be specific to each user, so it should be stored in the cookie or the session data. I recommend cookies because it stays each time after you restart your computer and you can also update it via Javascript from the client if need be.

We will store the cart as an associate array so each product ID has an associated quantity. For example, the cart array may look like:

["eggs" => 2, "flour" => 3, /* etc */ ]
Enter fullscreen mode Exit fullscreen mode

You may have noticed when sending data server-client or vice versa, everything is sent as a string. JSON is commonly used for encoding and decoding arrays at either end.

Add to Cart

Open the file index.php from the previous stage for editing in the following steps.

1. Add href attributes to the links above to link to edit_cart.php?id=# where # is the product ID.

    <div> <span>Product #1</span> <a href="edit_cart.php?id=1">Add to cart</a> </div>
    <div> <span>Product #2</span> <a href="edit_cart.php?id=2">Add to cart</a> </div>
    <div> <span>Product #3</span> <a href="edit_cart.php?id=3">Add to cart</a> </div>
Enter fullscreen mode Exit fullscreen mode

Create a file called edit_cart.php. Edit this file in the following steps.

2. Add PHP tags.

<?php ?>
Enter fullscreen mode Exit fullscreen mode

3. Notice that the links send the product ID via the GET protocol. Assign this value to a variable.

$productID = $_GET["id"];
Enter fullscreen mode Exit fullscreen mode

4. Get the cart out of the cookie and decode it from a JSON string into an array. If the cart cookie is empty, create an empty array.

$cart = json_decode($_COOKIE["cart"] ?? "{}", true);
Enter fullscreen mode Exit fullscreen mode

5. Create a new pair for the product ID with one quantity. If the product is already in the cart, don’t change the cart.

if (!isset($cart[$productID])) $cart[$productID] = 1;
Enter fullscreen mode Exit fullscreen mode

6. Encode the array back into a JSON string and save it in the cookie for ten days. Your site’s cookies are stored separate to other sites, so there won’t be conflict from a generic name like "cart". The last parameter "/" means the cookie is accessible by all (sub)pages of your site.

setcookie("cart", json_encode($cart), time() + 3600 * 24 * 10, "/");
Enter fullscreen mode Exit fullscreen mode

7. Redirect the user to the cart viewing page which we will call cart.php.

header("Location: cart.php");
Enter fullscreen mode Exit fullscreen mode

8. The final code:

<?php 
$productID = $_GET["id"];
$cart = json_decode($_COOKIE["cart"] ?? "{}", true);
if (!isset($cart[$productID])) $cart[$productID] = 1;
setcookie("cart", json_encode($cart), time() + 3600 * 24 * 10, "/");
header("Location: cart.php");
?>
Enter fullscreen mode Exit fullscreen mode

View Cart

Create a file called cart.php to edit in the following steps.

9. Add html, body and PHP elements.

<html><body><?php ?></body></html>
Enter fullscreen mode Exit fullscreen mode

10. Decode the cart cookie into an array and use a foreach loop to iterate over the elements.

$cart = json_decode($_COOKIE["cart"] ?? "{}", true);
foreach ($cart as $productID => $quantity) {
Enter fullscreen mode Exit fullscreen mode

11. Output the details with links to add, subtract and remove each item.

    echo "<div>";
    echo "<span>Product #$productID x$quantity</span>";
    echo "<a>Add</a> <a>Sub</a> <a>Remove</a>";
    echo "</div>";
}
Enter fullscreen mode Exit fullscreen mode

12. Add href attributes to add, subtract and remove items. We will adapt the add_to_cart.php file so it can do other cart manipulations. Send another GET attribute for the edit type.

    $editUrl = "edit_cart.php?id=$productID";
    echo "<a href='$editUrl&type=add'>Add</a>";
    echo "<a href='$editUrl&type=sub'>Sub</a>";
    echo "<a href='$editUrl&type=rem'>Remove</a>";
Enter fullscreen mode Exit fullscreen mode

Edit Cart More

Now open edit_cart.php for editing in the following steps:

13. Assign a variable for the edit type from step 13 under the $productID.

$editType = $_GET["type"];
Enter fullscreen mode Exit fullscreen mode

14. Use a switch statement on the edit type with 3 cases: "add", "sub" and "rem", after the cart variable is assigned and before the cart cookie is set, replacing the line if (!isset($cart...

switch ($editType) {
case "add":
    break;
case "sub":
    break;
case "rem":
    break;
}
Enter fullscreen mode Exit fullscreen mode

15. For the "add" case, increment the quantity if the product is already in the cart. Otherwise add a new key with a quantity of 1.

if (isset($cart[$productID])) $cart[$productID]++;
else $cart[$productID] = 1;
Enter fullscreen mode Exit fullscreen mode

16. For the "sub" case, decrement the quantity only if the product is already in the cart. Then, check if the quantity is invalid (zero or less) to remove the key from the cart array.

if (!isset($cart[$productID])) break;
$cart[$productID]--;
if ($cart[$productID] <= 0) unset($cart[$productID]);
break;
Enter fullscreen mode Exit fullscreen mode

17. For the "rem" case, remove the key from the cart array.

unset($cart[$productID]);
Enter fullscreen mode Exit fullscreen mode

18. Add two different products to your cart from the index page and then try adding, subtracting and removing from the cart page. The quantities should be updated accordingly.

19. The final code:

<?php 
$productID = $_GET["id"];
$editType = $_GET["type"];
$cart = json_decode($_COOKIE["cart"] ?? "{}", true);


switch ($editType) {
case "add":
    // Increment quantity of already added product.
    if (isset($cart[$productID])) $cart[$productID]++;
    // Otherwise put 1 quantity of product in cart.
    else $cart[$productID] = 1;
    break;
case "sub":
    if (!isset($cart[$productID])) break;
    // Decrement quantity of already added product
    $cart[$productID]--;
    if ($cart[$productID] <= 0)
        // If quantity is now 0, remove from cart.
        unset($cart[$productID]);
    break;
case "rem":
    unset($cart[$productID]);
    break;
}


setcookie("cart", json_encode($cart), time() + 3600 * 24 * 10, "/");
header("Location: cart.php");
?>
Enter fullscreen mode Exit fullscreen mode

Parent topic: Example 5

Top comments (0)