-
-
Save anonymous/fb3976461906ecc05098aacce98116e4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
session_start(); | |
$products = []; | |
$products[1] = array('name' => 'Bar Soap', 'price' => '4.50', 'weight' => '4'); | |
$products[2] = array('name' => 'Lotion', 'price' => '9.99', 'weight' => '8'); | |
$products[3] = array('name' => 'Liquid Soap', 'price' => '12.00', 'weight' => '10'); | |
function product_exists($product_id) { | |
global $products; | |
return array_key_exists($product_id, $products); | |
} | |
function product_in_cart($product_id) { | |
return array_key_exists($product_id, $_SESSION['cart']); | |
} | |
$product_id = $_GET['product_id']; //the product id from the URL | |
$action = $_GET['action']; //the action from the URL | |
switch ($action) { | |
case 'add': | |
if (product_exists($product_id)) { | |
if (!isset($_SESSION['cart'][$product_id])){ | |
$_SESSION['cart'][$product_id] = 0; | |
} | |
$_SESSION['cart'][$product_id]++; | |
} | |
break; | |
case 'update': | |
$quantity_array = $_POST['quantity']; | |
if (isset($quantity_array) && is_array($quantity_array)) { | |
foreach($quantity_array as $product_id => $quantity) { | |
if (product_exists($product_id) && product_in_cart($product_id)) { | |
$_SESSION['cart'][$product_id] = $quantity; | |
} | |
} | |
} | |
break; | |
case 'remove': | |
unset($_SESSION['cart'][$product_id]); | |
break; | |
case 'empty': | |
unset($_SESSION['cart']); | |
break; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment