diff --git a/cart.php b/cart.php index 4810016..ce6af8c 100644 --- a/cart.php +++ b/cart.php @@ -78,7 +78,7 @@ session_start();
- +
diff --git a/order.php b/order.php new file mode 100644 index 0000000..064877e --- /dev/null +++ b/order.php @@ -0,0 +1,135 @@ +begin_transaction(); + +try { + // Calcola il totale dell'ordine + foreach ($cart as $item) { + $order_total += $item['price'] * $item['quantity']; + } + + // Crea un nuovo ordine + $sql_order = "INSERT INTO Orders (UserID, Total, Status) VALUES (?, ?, 'pending')"; + $stmt_order = $conn->prepare($sql_order); + if (!$stmt_order) { + throw new Exception("Errore nella preparazione della query: " . $conn->error); + } + + $stmt_order->bind_param("id", $user_id, $order_total); + $stmt_order->execute(); + $order_id = $conn->insert_id; + + // Per ogni prodotto nel carrello + foreach ($cart as $item) { + $product_id = $item['id']; + $quantity = $item['quantity']; + $price = $item['price']; + + // Aggiungi item all'ordine + $sql_item = "INSERT INTO OrderItems (OrderID, ProductID, Quantity, Price) VALUES (?, ?, ?, ?)"; + $stmt_item = $conn->prepare($sql_item); + if (!$stmt_item) { + throw new Exception("Errore nella preparazione della query: " . $conn->error); + } + + $stmt_item->bind_param("iiii", $order_id, $product_id, $quantity, $price); + $stmt_item->execute(); + + // Riduci lo stock del prodotto + $sql_stock = "UPDATE Products SET StockQuantity = StockQuantity - ? WHERE ProductID = ?"; + $stmt_stock = $conn->prepare($sql_stock); + if (!$stmt_stock) { + throw new Exception("Errore nella preparazione della query: " . $conn->error); + } + + $stmt_stock->bind_param("ii", $quantity, $product_id); + $stmt_stock->execute(); + + $stmt_item->close(); + $stmt_stock->close(); + } + + // Conferma la transazione + $conn->commit(); + + // Svuota il carrello + setcookie('cart', '', time() - 3600, '/'); + + // Mostra pagina di successo + $success = true; + +} catch (Exception $e) { + // Annulla la transazione in caso di errore + $conn->rollback(); + $error = "Errore nell'elaborazione dell'ordine: " . $e->getMessage(); + $success = false; +} + +$stmt_order->close(); +$conn->close(); +?> + + + + + + + <?php echo $success ? 'Ordine confermato' : 'Errore ordine'; ?> - TechStore + + + +
+ +
+ + + + Benvenuto, + + + +
+
+ +
+ +

Ordine confermato!

+

Il tuo ordine è stato elaborato con successo.

+

Numero ordine: #

+

Totale:

+ + +

Errore nell'ordine

+

+ + +
+ + \ No newline at end of file