From d444b1191c22913ff44ae6b05187fc3a24100f58 Mon Sep 17 00:00:00 2001 From: chocbic172 Date: Fri, 22 Mar 2024 21:28:05 +0000 Subject: [PATCH] Implement checkout and order recording --- checklist.md | 2 +- root/cart.php | 41 +++++++++++++++++++++++++++++++++++++++-- root/styles/cart.css | 5 +++++ root/utils/database.php | 26 ++++++++++++++++++++++++++ 4 files changed, 71 insertions(+), 3 deletions(-) diff --git a/checklist.md b/checklist.md index a4ec13d..290e689 100644 --- a/checklist.md +++ b/checklist.md @@ -38,5 +38,5 @@ - [x] Product reviews / scores - [x] Verified users can post reviews - [x] Advanced search -- [ ] Checkout mechanism +- [x] Checkout mechanism - [x] Secure password storage / verification diff --git a/root/cart.php b/root/cart.php index d2260b1..84e88ac 100644 --- a/root/cart.php +++ b/root/cart.php @@ -9,6 +9,30 @@ $totalPrice = 0.0; +$userLoggedIn = isset($_SESSION['user']); + +$serverMessages = ""; + +if ($_SERVER["REQUEST_METHOD"] == "POST") { + if (!$userLoggedIn) { + $serverMessages .= "

Please log in (use the link in the navbar) to checkout your cart.

"; + } + + if ((!isset($_SESSION['cart'])) || (count($_SESSION['cart']) < 1)) { + $serverMessages .= "

Please add some orders to the basket to start checking out your product.

"; + $orderSuccess = false; + } else { + $orderSuccess = $db->saveOrder($_SESSION['cart']); + } + + if ($orderSuccess) { + $serverMessages .= "

Order successfully submitted! Thank you for shopping!

"; + unset($_SESSION['cart']); + } else { + $serverMessages .= "

Order could not be submitted :( Please refresh and try again.

"; + } +} + ?> @@ -29,6 +53,9 @@

Cart

+
+ +

- + Please log in to checkout your basket!" ?> + + +
" method="post"> + ' : "" ?> +
+

Forgotten something? Press here to continue shopping diff --git a/root/styles/cart.css b/root/styles/cart.css index 4aba297..3f5c04f 100644 --- a/root/styles/cart.css +++ b/root/styles/cart.css @@ -90,3 +90,8 @@ https://developer.mozilla.org/en-US/docs/Web/CSS/@import */ .cart-bottom a { color: var(--primary-blue); } + +.server-messages { + text-align: center; + font-size: 1.25em; +} diff --git a/root/utils/database.php b/root/utils/database.php index daa4ee2..fd0b21c 100644 --- a/root/utils/database.php +++ b/root/utils/database.php @@ -304,4 +304,30 @@ public function getRatingForProduct(string $productId) { return $rating[0]; } + + /** + * Stored an order to the database + * + * @param array $basket array of product ids to be ordered + * + * @return boolean whether the creation of the order was successful + */ + public function saveOrder(array $basket) { + $sql_query = $this->conn->prepare("INSERT INTO ".$this->orders_table. + " (`order_id`, `order_date`, `user_id`, `product_ids`) + VALUES (NULL, current_timestamp(), ?, ?)"); + + $query_success = $sql_query->execute([ + $_SESSION['user'], + json_encode($basket), + ]); + + if (!$query_success) { + $sql_query->close(); + return false; + } + + $sql_query->close(); + return true; + } }