E5 - Temporary Shopping Cart
Tags: php, tutorial
Published: 2020-04-15 19:09:17

The cart is a tricky process requiring many steps.
Jump to section:
* [Explanation of Shopping Cart](#explanation)
* [Add to Cart](#add-to-cart)
* [View Cart](#view-cart)
* [Edit Cart More](#more-cart-edit)

## Explanation of Shopping Cart <a name="explanation"></a>

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:
```php
["eggs" => 2, "flour" => 3, /* etc */ ]
```

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 <a name="add-to-cart"></a>

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

1.&nbsp;Add href attributes to the links above to link to `edit_cart.php?id=#` where # is the product ID.
```php
    <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>
```

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

2.&nbsp;Add PHP tags.
```php
<?php ?>
```

3.&nbsp;Notice that the links send the product ID via the GET protocol. Assign this value to a variable.
```php
$productID = $_GET["id"];
```

4.&nbsp;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.
```php
$cart = json_decode($_COOKIE["cart"] ?? "{}", true);
```

5.&nbsp;Create a new pair for the product ID with one quantity. If the product is already in the cart, don’t change the cart.
```php
if (!isset($cart[$productID])) $cart[$productID] = 1;
```

6.&nbsp;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.
```php
setcookie("cart", json_encode($cart), time() + 3600 * 24 * 10, "/");
```

7.&nbsp;Redirect the user to the cart viewing page which we will call `cart.php`.
```php
header("Location: cart.php");
```

8.&nbsp;The final code:
```php
<?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");
?>
```

## View Cart <a name="view-cart"></a>

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

9.&nbsp;Add html, body and PHP elements.
```php
<html><body><?php ?></body></html>
```

10.&nbsp;Decode the cart cookie into an array and use a foreach loop to iterate over the elements.
```php
$cart = json_decode($_COOKIE["cart"] ?? "{}", true);
foreach ($cart as $productID => $quantity) {
```

11.&nbsp;Output the details with links to add, subtract and remove each item.
```php
    echo "<div>";
    echo "<span>Product #$productID x$quantity</span>";
    echo "<a>Add</a> <a>Sub</a> <a>Remove</a>";
    echo "</div>";
}
```

12.&nbsp;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.
```php
    $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>";
```

## Edit Cart More <a name="more-cart-edit"></a>

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

13.&nbsp;Assign a variable for the edit type from step 13 under the `$productID`.
```php
$editType = $_GET["type"];
```

14.&nbsp;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...`
```php
switch ($editType) {
case "add":
    break;
case "sub":
    break;
case "rem":
    break;
}
```

15.&nbsp;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.
```php
if (isset($cart[$productID])) $cart[$productID]++;
else $cart[$productID] = 1;
```

16.&nbsp;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.
```php
if (!isset($cart[$productID])) break;
$cart[$productID]--;
if ($cart[$productID] <= 0) unset($cart[$productID]);
break;
```

17.&nbsp;For the "rem" case, remove the key from the cart array.
```php
unset($cart[$productID]);
```

18.&nbsp;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.&nbsp;The final code:
```php
<?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");
?>
```

Parent topic: [Example 5](https://dev.to/herobank110/exercise-5-shopping-facility-443n)