function addToCart() { //Function for adding a product to the cart based on that products ID. //Create the MYSQL db connection $db = new mysqli(DB_HOST, DB_USER, DB_PASS, T4_DB_NAME); //Check if the ID variable is set if (isset($_GET['ID'])) { //Escape the string from the URL $ID = $db->real_escape_string($_GET['ID']); //Check if the ID passed exists within the database $result = $db->query('SELECT * FROM products WHERE ID = "' . $ID . '" LIMIT 1'); //If the product ID exists in the database then insert it to the cart if ($result->num_rows > 0) { while ($row = $result->fetch_object()) { //Check if the cart exists if (cartExists()) { //The cart exists so just add it to the cart insertToCart($ID, $row->name, $row->price); } else { //The cart doesn't exist so create the cart createCart(); //The cart is now created so add the product to the cart insertToCart($ID, $row->name, $row->price); } } } else { //No products were found in the database so notify the user, redirect him and stop the code from continuing notify('Sorry but there is no product with that ID.', 0); header('Location: tutorial-4.php'); break; } //The product was successfully added so set the notification and redirect to the cart page notify('Product added to the cart.', 1); header('Location: cart.php'); } else { //No Product with that ID redirect and display message notify('Sorry but there is no product with that ID.', 0); header('Location: tutorial-4.php'); } }
$cart = createCart(); } $item = isset($_POST['item']) ? $_POST['item'] : ''; $mode = isset($_POST['mode']) ? $_POST['mode'] : ''; switch ($mode) { case 'add': echo '<p style="color: #aa0000">追加しました</p>'; $cart->addItem($item); break; case 'remove': echo '<p style="color: #008800">削除しました</p>'; $cart->removeItem($item); break; case 'clear': echo '<p style="color: #008800">クリアしました</p>'; $cart = createCart(); break; } $_SESSION['cart'] = $cart; echo '<h1>商品一覧</h1>'; echo '<ul>'; foreach ($cart->getItems() as $item_name => $quantity) { echo '<li>' . $item_name . ' ' . $quantity . '個</li>'; } ?> <form action="" method="post"> <select name="item"> <option value="10:Tシャツ">Tシャツ</option> <option value="20:ぬいぐるみ">ぬいぐるみ</option> <option value="30:クッキーセット">クッキーセット</option> </select>