|
| 1 | +<?php |
| 2 | + session_start(); |
| 3 | + if(isset($_GET['reset'])){ |
| 4 | + unset($_SESSION['food']); |
| 5 | + unset($_SESSION['itemlist']); |
| 6 | + } |
| 7 | +?> |
| 8 | +<!DOCTYPE html> |
| 9 | +<html lang="en"> |
| 10 | +<head> |
| 11 | + <meta charset="UTF-8"> |
| 12 | + <meta http-equiv="X-UA-Compatible" content="IE=edge"> |
| 13 | + <meta name="viewport" content="width=device-width, initial-scale=1.0"> |
| 14 | + <title>Php - Simple shopping cart reference</title> |
| 15 | + <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"> |
| 16 | +</head> |
| 17 | +<body> |
| 18 | + <div class="container my-5"> |
| 19 | + <a href="?cart=<?php echo rand(1, 5); ?>" class="btn btn-info me-3">Add to Cart</a> |
| 20 | + <a href="?reset" class="btn btn-warning">Reset</a> |
| 21 | + </div> |
| 22 | + <hr> |
| 23 | + <div class="container my-5"> |
| 24 | + <?php |
| 25 | + $color = ['red', 'green', 'blue', 'orange', 'purple', 'sky', 'yellow', 'aliceblue', 'dark', 'gray']; |
| 26 | + if(isset($_GET['cart'])){ |
| 27 | + $product = $_GET['cart']; |
| 28 | + foreach($color as $key => $colorValue){ |
| 29 | + if($product == $key){ |
| 30 | + $name = $colorValue; |
| 31 | + break; |
| 32 | + } |
| 33 | + } |
| 34 | + $cartArray = [$product=>['id'=>$product, 'name'=>$name]]; |
| 35 | + if(empty( $_SESSION['itemlist'])){ |
| 36 | + $_SESSION['itemlist'][$product] = $product; |
| 37 | + $_SESSION['food'] = $cartArray; |
| 38 | + }else{ |
| 39 | + if(in_array($product, $_SESSION['itemlist'])){ |
| 40 | + $msg = "Already exist"; |
| 41 | + }else{ |
| 42 | + $_SESSION['itemlist'][$product] = $product; |
| 43 | + $_SESSION["food"] = array_merge($_SESSION["food"],$cartArray); // array_replace() can be use as well. it will preserve "key". unlike array_combine() which reset index |
| 44 | + $msg = "New"; |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + echo $msg ."<br>"; |
| 49 | + |
| 50 | + echo "<pre>"; |
| 51 | + echo print_r($_SESSION['food']); |
| 52 | + echo "</pre>"; |
| 53 | + } |
| 54 | + |
| 55 | + echo "<br><br>"; |
| 56 | + |
| 57 | + foreach($color as $key => $colorValue){ |
| 58 | + echo "Product ID: ".$key."<br>"; |
| 59 | + echo "Product Name: ".$colorValue."<br>"; |
| 60 | + } |
| 61 | + ?> |
| 62 | + </div> |
| 63 | + <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script> |
| 64 | + <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> |
| 65 | +</body> |
| 66 | +</html> |
0 commit comments