Skip to content

Instantly share code, notes, and snippets.

@Slaver
Created July 3, 2024 21:37
Show Gist options
  • Save Slaver/7bc9a3d974aa43e24ef3dad9728485de to your computer and use it in GitHub Desktop.
Save Slaver/7bc9a3d974aa43e24ef3dad9728485de to your computer and use it in GitHub Desktop.
<?php
class OrderProcessor
{
public function processOrder($orderId, $items, $customerEmail)
{
// Check if product exists
foreach ($items as $item) {
$sql = "SELECT quantity FROM products WHERE id = " . $item['id'];
$result = mysqli_query($GLOBALS['db_connection'], $sql);
$row = mysqli_fetch_assoc($result);
if ($row['quantity'] < $item['quantity']) {
die("Not enough stock for product " . $item['id']);
}
}
// Create a new order
$totalPrice = 0;
foreach ($items as $item) {
$totalPrice += $item['price'] * $item['quantity'];
}
$sql = "INSERT INTO orders (customer_email, total_price, status) VALUES ('$customerEmail', $totalPrice, 'pending')";
mysqli_query($GLOBALS['db_connection'], $sql);
$orderId = mysqli_insert_id($GLOBALS['db_connection']);
// Update product amount
foreach ($items as $item) {
$sql = "UPDATE products SET quantity = quantity - " . $item['quantity'] . " WHERE id = " . $item['id'];
mysqli_query($GLOBALS['db_connection'], $sql);
}
// Send email
mail($customerEmail, "Order Confirmation", "Your order #$orderId has been placed. Total: $totalPrice");
return "Order processed successfully";
}
}
// Run
$processor = new OrderProcessor();
$result = $processor->processOrder(1, array(
array('id' => 1, 'quantity' => 2, 'price' => 10),
array('id' => 2, 'quantity' => 1, 'price' => 20)
), "customer@example.com");
echo $result;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment