Repository navigation
Expand file tree
/
Copy pathupdate_cart.php
More file actions
73 lines (62 loc) · 2.32 KB
/
Copy pathupdate_cart.php
File metadata and controls
73 lines (62 loc) · 2.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<?php
// AI tools were used during development to assist developers
// Robert Walters and Thadd McLeod
require_once "config.php";
require_once "CartClass.php";
require_once "ProductRepo.php";
session_start();
$redirect = $_POST['redirect_to'] ?? "cart.php";
$productId = $_POST['id'];
$action = $_POST['action'];
$cartQty = $_POST['qty'] ?? null;
$stockQty = $_POST['stock-qty'] ?? null;
//establish database connection
$mysqli = db::getDB();
// Initialize ProductRepo with database connection
$productRepo = new ProductRepo($mysqli);
$product = $productRepo->findProductByID($productId);
$cart = $_SESSION['cart'];
// session update
if ($action === 'increase' && $stockQty > $cartQty) {
$cart->addProduct($product);
} else if ($action === "decrease") {
$cart->decreaseProductQty($product);
} else if ($action === "remove") {
$cart->removeProduct($product);
}
// DB update if logged in
if (isset($_SESSION['user'])) {
$cart_id = $_SESSION['cart_id'];
if ($action === "increase") {
$stmt = $mysqli->prepare("UPDATE cart_items SET quantity = quantity + 1
WHERE cart_id = ? AND product_id = ?");
$stmt->bind_param("ii", $cart_id, $productId);
$stmt->execute();
}
if ($action === "decrease") {
// check current qty
$stmt = $mysqli->prepare("SELECT quantity FROM cart_items WHERE cart_id = ? AND product_id = ?");
$stmt->bind_param("ii", $cart_id, $productId);
$stmt->execute();
$qty = $stmt->get_result()->fetch_assoc()['quantity'];
if ($qty <= 1) {
// remove
$stmt = $mysqli->prepare("DELETE FROM cart_items WHERE cart_id = ? AND product_id = ?");
$stmt->bind_param("ii", $cart_id, $productId);
$stmt->execute();
} else {
$stmt = $mysqli->prepare("UPDATE cart_items SET quantity = quantity - 1
WHERE cart_id = ? AND product_id = ?");
$stmt->bind_param("ii", $cart_id, $productId);
$stmt->execute();
}
}
if ($action === "remove") {
$stmt = $mysqli->prepare("DELETE FROM cart_items WHERE cart_id = ? AND product_id = ?");
$stmt->bind_param("ii", $cart_id, $productId);
$stmt->execute();
}
}
$_SESSION['cart'] = $cart;
header("Location: $redirect");
exit;