php实现商品批发
PHP实现商品批发的核心逻辑
商品批发功能通常涉及批量价格计算、订单处理和数据展示。以下是实现的关键步骤:
数据库表设计
创建商品表和批发价格规则表是基础。商品表存储基本信息,批发价格规则表定义不同数量的价格阶梯。
商品表结构示例:
CREATE TABLE products (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),
retail_price DECIMAL(10,2),
description TEXT
);
批发规则表结构:
CREATE TABLE wholesale_rules (
id INT AUTO_INCREMENT PRIMARY KEY,
product_id INT,
min_quantity INT,
unit_price DECIMAL(10,2),
FOREIGN KEY (product_id) REFERENCES products(id)
);
批发价格计算逻辑
通过查询批发规则表实现动态价格计算。根据购买数量匹配对应的价格阶梯。
function calculateWholesalePrice($productId, $quantity) {
$db = new PDO('mysql:host=localhost;dbname=your_db', 'username', 'password');
// 获取所有适用于该商品的批发规则,按数量降序排列
$stmt = $db->prepare("
SELECT * FROM wholesale_rules
WHERE product_id = :product_id AND min_quantity <= :quantity
ORDER BY min_quantity DESC
LIMIT 1
");
$stmt->execute([':product_id' => $productId, ':quantity' => $quantity]);
$rule = $stmt->fetch(PDO::FETCH_ASSOC);
if ($rule) {
return $quantity * $rule['unit_price'];
} else {
// 没有批发规则则使用零售价
$stmt = $db->prepare("SELECT retail_price FROM products WHERE id = :product_id");
$stmt->execute([':product_id' => $productId]);
$product = $stmt->fetch(PDO::FETCH_ASSOC);
return $quantity * $product['retail_price'];
}
}
前端交互实现
使用JavaScript实现实时价格计算,提升用户体验。
<div class="product">
<h3><?php echo $product['name']; ?></h3>
<input type="number" id="quantity" min="1" value="1">
<button onclick="calculatePrice(<?php echo $product['id']; ?>)">计算批发价</button>
<div id="priceResult"></div>
</div>
<script>
function calculatePrice(productId) {
const quantity = document.getElementById('quantity').value;
fetch(`calculate_price.php?product_id=${productId}&quantity=${quantity}`)
.then(response => response.json())
.then(data => {
document.getElementById('priceResult').innerHTML =
`总价: ${data.total_price}`;
});
}
</script>
后端价格计算接口
创建独立的PHP接口处理价格计算请求。
// calculate_price.php
header('Content-Type: application/json');
$productId = $_GET['product_id'] ?? 0;
$quantity = $_GET['quantity'] ?? 1;
$totalPrice = calculateWholesalePrice($productId, $quantity);
echo json_encode([
'product_id' => $productId,
'quantity' => $quantity,
'total_price' => number_format($totalPrice, 2)
]);
批量订单处理
批发订单通常包含多个商品和大量数量,需要特殊处理。
function createWholesaleOrder($customerId, $items) {
$db = new PDO('mysql:host=localhost;dbname=your_db', 'username', 'password');
try {
$db->beginTransaction();
// 创建订单主记录
$stmt = $db->prepare("
INSERT INTO orders (customer_id, order_date, status)
VALUES (:customer_id, NOW(), 'pending')
");
$stmt->execute([':customer_id' => $customerId]);
$orderId = $db->lastInsertId();
// 添加订单明细
foreach ($items as $item) {
$price = calculateWholesalePrice($item['product_id'], $item['quantity']);
$stmt = $db->prepare("
INSERT INTO order_items (order_id, product_id, quantity, unit_price)
VALUES (:order_id, :product_id, :quantity, :unit_price)
");
$stmt->execute([
':order_id' => $orderId,
':product_id' => $item['product_id'],
':quantity' => $item['quantity'],
':unit_price' => $price / $item['quantity']
]);
}
$db->commit();
return $orderId;
} catch (Exception $e) {
$db->rollBack();
throw $e;
}
}
数据可视化展示
为批发商提供销售数据统计视图,辅助决策。
function getWholesaleSalesReport($startDate, $endDate) {
$db = new PDO('mysql:host=localhost;dbname=your_db', 'username', 'password');
$stmt = $db->prepare("
SELECT p.name, SUM(oi.quantity) as total_quantity,
SUM(oi.quantity * oi.unit_price) as total_revenue
FROM order_items oi
JOIN orders o ON oi.order_id = o.id
JOIN products p ON oi.product_id = p.id
WHERE o.order_date BETWEEN :start_date AND :end_date
GROUP BY oi.product_id
ORDER BY total_revenue DESC
");
$stmt->execute([
':start_date' => $startDate,
':end_date' => $endDate
]);
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
以上实现涵盖了商品批发系统的主要功能模块,可根据实际需求进行调整和扩展。重点在于批发规则管理、批量价格计算和高效订单处理。数据库优化和缓存策略对大批量数据处理尤为重要。







