-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaddToCart.php
More file actions
50 lines (44 loc) · 1.44 KB
/
Copy pathaddToCart.php
File metadata and controls
50 lines (44 loc) · 1.44 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
<?php
// Start the session to access session variables
session_start();
// Check if the form is submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Retrieve book details from the form
$bookId = $_POST['book_id'];
$title = $_POST['title'];
$price = $_POST['price'];
// Create a new cart item
$cartItem = array(
'book_id' => $bookId,
'title' => $title,
'price' => $price,
'quantity' => 1 // You can set the initial quantity as needed
);
// Check if the cart session variable exists
if (!isset($_SESSION['cart'])) {
// If not, create an empty cart array
$_SESSION['cart'] = array();
}
// Check if the book is already in the cart
$bookInCart = false;
foreach ($_SESSION['cart'] as &$item) {
if ($item['book_id'] === $bookId) {
// If the book is already in the cart, increment the quantity
$item['quantity']++;
$bookInCart = true;
break;
}
}
// If the book is not in the cart, add it as a new item
if (!$bookInCart) {
$_SESSION['cart'][] = $cartItem;
}
// Redirect back to the previous page or a confirmation page
header("Location: " . $_SERVER["HTTP_REFERER"]);
exit();
} else {
// If the form is not submitted, redirect to the homepage or an error page
header("Location: index.php"); // Change "index.php" to your homepage or error page
exit();
}
?>