php实现折扣商品
实现折扣商品功能
在PHP中实现折扣商品功能,通常涉及数据库设计、价格计算逻辑和前端展示。以下是具体实现方法:
数据库设计 创建商品表时需包含折扣相关字段:

CREATE TABLE products (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
original_price DECIMAL(10,2) NOT NULL,
discount_price DECIMAL(10,2),
discount_percentage INT,
is_discounted BOOLEAN DEFAULT 0,
discount_start DATE,
discount_end DATE
);
价格计算逻辑 在商品模型中添加折扣计算逻辑:
class Product {
public function getCurrentPrice() {
if ($this->isDiscounted() && $this->isDiscountActive()) {
return $this->discount_price ??
$this->original_price * (1 - $this->discount_percentage/100);
}
return $this->original_price;
}
private function isDiscountActive() {
$now = date('Y-m-d');
return (!$this->discount_start || $this->discount_start <= $now) &&
(!$this->discount_end || $this->discount_end >= $now);
}
}
前端展示 在商品展示页面突出显示折扣信息:

<div class="product">
<h3><?= htmlspecialchars($product->name) ?></h3>
<?php if ($product->isDiscounted() && $product->isDiscountActive()): ?>
<span class="original-price"><?= number_format($product->original_price, 2) ?></span>
<span class="discount-price"><?= number_format($product->getCurrentPrice(), 2) ?></span>
<?php if ($product->discount_percentage): ?>
<span class="discount-badge">-<?= $product->discount_percentage ?>%</span>
<?php endif; ?>
<?php else: ?>
<span class="price"><?= number_format($product->original_price, 2) ?></span>
<?php endif; ?>
</div>
定时任务处理 使用cron job自动更新折扣状态:
// 在cron job中执行的脚本
$expiredProducts = Product::where('discount_end', '<', date('Y-m-d'))
->where('is_discounted', 1)
->get();
foreach ($expiredProducts as $product) {
$product->update([
'is_discounted' => 0,
'discount_price' => null,
'discount_percentage' => null
]);
}
API接口 为移动应用提供折扣商品接口:
$router->get('/api/discounted-products', function() {
$products = Product::where('is_discounted', 1)
->where(function($query) {
$query->whereNull('discount_start')
->orWhere('discount_start', '<=', date('Y-m-d'));
})
->where(function($query) {
$query->whereNull('discount_end')
->orWhere('discount_end', '>=', date('Y-m-d'));
})
->get();
return response()->json($products);
});






