-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfirmPurchase.php
More file actions
83 lines (68 loc) · 2.36 KB
/
confirmPurchase.php
File metadata and controls
83 lines (68 loc) · 2.36 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
74
75
76
77
78
79
80
81
82
83
<?php
session_start();
// Check if the user is logged in
$is_logged_in = isset($_SESSION['username']);
$username = $is_logged_in ? $_SESSION['username'] : null;
if (!$is_logged_in) {
header("Location: login.php");
exit();
}
if (isset($_GET['logout'])) {
session_unset();
session_destroy();
header("Location: index.php");
exit();
}
// Database connection
$servername = "localhost";
$usernameDB = "root";
$passwordDB = "";
$database = "library";
$conn = new mysqli($servername, $usernameDB, $passwordDB, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Get UserID from the database using the username
$username = $_SESSION['username'];
$query = "SELECT UserID FROM user WHERE Username = '$username'";
$result = mysqli_query($conn, $query);
if ($result && mysqli_num_rows($result) > 0) {
$user = mysqli_fetch_assoc($result);
$userID = $user['UserID'];
} else {
die("User not found in the database.");
}
// Handle book purchase
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['BookID'], $_POST['quantity']) && is_numeric($_POST['quantity'])) {
$bookID = $_POST['BookID'];
$quantityPurchased = $_POST['quantity'];
// Fetch book details
$query = "SELECT * FROM book WHERE BookID = $bookID";
$result = mysqli_query($conn, $query);
if ($result && mysqli_num_rows($result) > 0) {
$book = mysqli_fetch_assoc($result);
$bookQuantity = $book['Quantity'];
$bookPrice = $book['Price'];
if ($bookQuantity >= $quantityPurchased) {
// Update book quantity
$newQuantity = $bookQuantity - $quantityPurchased;
$updateQuery = "UPDATE book SET Quantity = $newQuantity WHERE BookID = $bookID";
mysqli_query($conn, $updateQuery);
// Insert transaction
$totalPrice = $bookPrice * $quantityPurchased;
$purchaseQuery = "INSERT INTO purchase_transaction (UserID, BookID, Quantity, TotalPrice)
VALUES ($userID, $bookID, $quantityPurchased, $totalPrice)";
mysqli_query($conn, $purchaseQuery);
header("Location: purchaseSuccess.php");
exit();
} else {
echo "Insufficient stock.";
}
} else {
echo "Book not found!";
}
} else {
echo "Invalid request.";
}
$conn->close();
?>