-
Notifications
You must be signed in to change notification settings - Fork 0
/
cart_add.php
65 lines (53 loc) · 1.48 KB
/
cart_add.php
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
<?php
include 'includes/session.php';
$conn = $pdo->open();
$output = array('error'=>false);
$id = $_POST['id'];
$quantity = $_POST['quantity'];
if(isset($_SESSION['user'])){
$stmt = $conn->prepare("SELECT *, COUNT(*) AS numrows FROM cart WHERE user_id=:user_id AND product_id=:product_id");
$stmt->execute(['user_id'=>$user['id'], 'product_id'=>$id]);
$row = $stmt->fetch();
if($row['numrows'] < 1){
try{
$stmt = $conn->prepare("INSERT INTO cart (user_id, product_id, quantity) VALUES (:user_id, :product_id, :quantity)");
$stmt->execute(['user_id'=>$user['id'], 'product_id'=>$id, 'quantity'=>$quantity]);
$output['message'] = 'Item added to cart';
}
catch(PDOException $e){
$output['error'] = true;
$output['message'] = $e->getMessage();
}
}
else{
$output['error'] = true;
$output['message'] = 'Product already in cart';
}
}
else{
if(!isset($_SESSION['cart'])){
$_SESSION['cart'] = array();
}
$exist = array();
foreach($_SESSION['cart'] as $row){
array_push($exist, $row['productid']);
}
if(in_array($id, $exist)){
$output['error'] = true;
$output['message'] = 'Product already in cart';
}
else{
$data['productid'] = $id;
$data['quantity'] = $quantity;
if(array_push($_SESSION['cart'], $data)){
$output['message'] = 'Item added to cart';
}
else{
$output['error'] = true;
$output['message'] = 'Cannot add item to cart';
}
}
}
$pdo->close();
echo json_encode($output);
?>