PHP中下单功能实现
PHP下单功能实现步骤
数据库设计
创建订单表(orders)和订单详情表(order_items)是基础。orders表包含订单ID、用户ID、总金额、状态等字段;order_items表包含商品ID、订单ID、数量、单价等。
CREATE TABLE orders (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
total DECIMAL(10,2) NOT NULL,
status VARCHAR(20) DEFAULT 'pending',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE order_items (
id INT AUTO_INCREMENT PRIMARY KEY,
order_id INT NOT NULL,
product_id INT NOT NULL,
quantity INT NOT NULL,
price DECIMAL(10,2) NOT NULL
);
表单处理
前端提交订单数据通常通过POST请求。需要验证用户输入并过滤数据防止SQL注入。

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$userId = filter_input(INPUT_POST, 'user_id', FILTER_VALIDATE_INT);
$products = $_POST['products']; // 数组形式 [['id'=>1, 'quantity'=>2], ...]
if (!$userId || empty($products)) {
die('Invalid input');
}
}
事务处理
使用数据库事务确保订单和订单详情同时成功或失败。
try {
$pdo->beginTransaction();
// 计算总金额
$total = 0;
foreach ($products as $product) {
$stmt = $pdo->prepare("SELECT price FROM products WHERE id = ?");
$stmt->execute([$product['id']]);
$productData = $stmt->fetch();
$total += $productData['price'] * $product['quantity'];
}
// 插入订单
$stmt = $pdo->prepare("INSERT INTO orders (user_id, total) VALUES (?, ?)");
$stmt->execute([$userId, $total]);
$orderId = $pdo->lastInsertId();
// 插入订单详情
foreach ($products as $product) {
$stmt = $pdo->prepare("SELECT price FROM products WHERE id = ?");
$stmt->execute([$product['id']]);
$productData = $stmt->fetch();
$stmt = $pdo->prepare("INSERT INTO order_items (order_id, product_id, quantity, price) VALUES (?, ?, ?, ?)");
$stmt->execute([$orderId, $product['id'], $product['quantity'], $productData['price']]);
}
$pdo->commit();
echo "Order created successfully!";
} catch (Exception $e) {
$pdo->rollBack();
echo "Error: " . $e->getMessage();
}
库存更新
下单后需要更新商品库存,避免超卖。

foreach ($products as $product) {
$stmt = $pdo->prepare("UPDATE products SET stock = stock - ? WHERE id = ? AND stock >= ?");
$stmt->execute([$product['quantity'], $product['id'], $product['quantity']]);
if ($stmt->rowCount() == 0) {
throw new Exception("Insufficient stock for product ID: " . $product['id']);
}
}
订单状态管理
实现订单状态变更功能,如支付、发货、完成等。
function updateOrderStatus($orderId, $status) {
$allowedStatuses = ['pending', 'paid', 'shipped', 'completed', 'cancelled'];
if (!in_array($status, $allowedStatuses)) {
throw new InvalidArgumentException("Invalid status");
}
$stmt = $pdo->prepare("UPDATE orders SET status = ? WHERE id = ?");
$stmt->execute([$status, $orderId]);
return $stmt->rowCount() > 0;
}
安全措施
实施CSRF防护和输入验证。
session_start();
// 生成CSRF令牌
if (empty($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
// 验证CSRF令牌
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
die('CSRF token validation failed');
}
}






