// ========================= // PLACE ORDER (CLEAN + SAFE) // ========================= if (isset($_POST['place_order'])) { if (empty($_SESSION['cart'])) { echo ""; exit(); } $name = $_POST['name']; $phone = $_POST['phone']; $email = $_POST['email']; $address = $_POST['address']; $payment = $_POST['payment']; $order_id = uniqid("ORD"); $total = 0; $conn->begin_transaction(); try { // ========================= // 1. CALCULATE TOTAL (single query per product) // ========================= $productStmt = $conn->prepare("SELECT name, price FROM products WHERE id=?"); foreach ($_SESSION['cart'] as $product_id => $qty) { $productStmt->bind_param("i", $product_id); $productStmt->execute(); $result = $productStmt->get_result(); $product = $result->fetch_assoc(); if (!$product) { throw new Exception("Invalid product in cart"); } $total += $product['price'] * $qty; } $productStmt->close(); // ========================= // 2. INSERT ORDER // ========================= $orderStmt = $conn->prepare(" INSERT INTO orders (order_id, customer_name, phone, email, address, total, payment_method, status) VALUES (?, ?, ?, ?, ?, ?, ?, 'Pending') "); $orderStmt->bind_param( "sssssds", $order_id, $name, $phone, $email, $address, $total, $payment ); if (!$orderStmt->execute()) { throw new Exception("Order insert failed"); } $orderStmt->close(); // ========================= // 3. INSERT ORDER ITEMS // ========================= $itemStmt = $conn->prepare(" INSERT INTO order_items (order_id, product_id, product_name, price, quantity) VALUES (?, ?, ?, ?, ?) "); foreach ($_SESSION['cart'] as $product_id => $qty) { $productStmt = $conn->prepare("SELECT name, price FROM products WHERE id=?"); $productStmt->bind_param("i", $product_id); $productStmt->execute(); $product = $productStmt->get_result()->fetch_assoc(); $productStmt->close(); if (!$product) continue; $itemStmt->bind_param( "sisdi", $order_id, $product_id, $product['name'], $product['price'], $qty ); if (!$itemStmt->execute()) { throw new Exception("Order item insert failed"); } } $itemStmt->close(); // ========================= // 4. COMMIT // ========================= $conn->commit(); unset($_SESSION['cart']); echo ""; exit(); } catch (Exception $e) { $conn->rollback(); // log error (optional but recommended) error_log("Order Error: " . $e->getMessage()); echo ""; } }