-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathinsertBought.php
74 lines (63 loc) · 2.53 KB
/
insertBought.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
66
67
68
69
70
71
72
73
74
<?php
// insertBought.php
// Shannen Cawley - Handles insertion of items into the user's bought list, ensuring no duplicates
session_start();
include 'mylib.php'; // Include your database connection file
db_connect(); // Establish the database connection
global $db; // Use the global $db variable for the connection
// Check if the user is logged in
if (!isset($_SESSION['email'])) {
echo json_encode(["status" => "error", "message" => "User not logged in."]);
exit();
}
// Get the logged-in user's email from the session
$userEmail = $_SESSION['email'];
// Fetch the UserID from the `users` table based on the email
$sql = "SELECT UserID FROM users WHERE email = ?";
$stmt = $db->prepare($sql);
$stmt->bind_param("s", $userEmail);
$stmt->execute();
$stmt->bind_result($userID);
$stmt->fetch();
$stmt->close();
if (!$userID) {
echo json_encode(["status" => "error", "message" => "User not found."]);
exit();
}
// Check if the necessary POST parameters are set
if (isset($_POST['item_url']) && isset($_POST['item_title']) && isset($_POST['item_src'])) {
// Retrieve data from the POST request
$itemUrl = $_POST['item_url'];
$itemTitle = $_POST['item_title'];
$itemSrc = $_POST['item_src'];
// Check if the item is already in the user's bought list
$sql = "SELECT * FROM bought WHERE UserID = ? AND itemUrl = ?";
$stmt = $db->prepare($sql);
$stmt->bind_param("is", $userID, $itemUrl);
$stmt->execute();
$result = $stmt->get_result();
// If the item is already in the list, send a duplicate message
if ($result->num_rows > 0) {
echo json_encode(["status" => "duplicate", "message" => "This item is already in your bought list."]);
} else {
// Insert the new item into the bought list
$sql = "INSERT INTO bought (UserID, itemUrl, itemTitle, itemSrc) VALUES (?, ?, ?, ?)";
$stmt = $db->prepare($sql);
$stmt->bind_param('isss', $userID, $itemUrl, $itemTitle, $itemSrc);
// Check if the insertion was successful
if ($stmt->execute()) {
echo json_encode(["status" => "success", "message" => "Item added to bought list!"]);
} else {
// Error in insertion
echo json_encode(["status" => "error", "message" => "Error adding item to bought list."]);
}
}
// Close the statement and the connection
$stmt->close();
} else {
// Missing required POST parameters
echo json_encode(["status" => "error", "message" => "Missing required parameters."]);
}
// Close the database connection
$db->close();
?>