首页 > 解决方案 > 显示优惠券

问题描述

所以我有这个 MySQL 表,其中一个项目有一个名为isCoupon. 如果卖家不让该项目可用于优惠券使用,则默认设置为 0。每件商品都按 ID 订购,在商店中,可以有不止一张优惠券,该商品也可以打折。但是,当包含该项目时,如何使这些优惠券显示?我如何让买家选择要使用的优惠券?如果我将“50% off”而不是 0.5 记录在案,我如何计算新价格?

餐桌优惠券

couponCode | items | discount
------------------------------
SAMPLE123  | 1     | 50% off
SAMPLE234  | 2,3   | 40% off
SAMPLE345  | 1,5   | 25% off

表项

itemID | isCoupon
-----------------
1      | 1
2      | 1
3      | 1
4      | 0
5      | 1

谢谢!

标签: phpmysql

解决方案


试试下面的。至于买家选择哪张优惠券,应该让买家先选择商品,然后通过选择优惠券进入结账页面。

$num_items = 5;
// the below array is used to store the coupons you can use for the item so you can
// proceed with it to the checkout page, there you can make a select dropdown to let
// the buyer select which coupon to use
$coupon_use = array();
for($i = 0; $i < $num_items; $i++) {
    // check for current item
    $SQL = "SELECT * FROM item WHERE itemID = '$i'";
    $result = mysqli_query($connect, $SQL);
    $field = mysqli_fetch_assoc($result);
    // check if there is a coupon for the current item
    if($field['isCoupon'] == 1) {
        $SQL2 = "SELECT * FROM coupon";
        $result2 = mysqli_query($connect, $SQL2);
        // while method to go through every single coupon
        while($field2 = mysqli_fetch_assoc($result2)) {
            // if you put commas, you can use the explode method
            // to store all the items for that coupon and use it to
            // check for that current item
            $coupons = explode(',', $field2['items']);
            if(in_array($i, $coupons)) {
                // do your items have a price?
                // salePrice is the new price
                // thePrice is the old price you need to get with $field (not $field2)
                if($field2['discount'] == '50% off') { $salePrice = $thePrice * 0.5; }
                else if($field2['discount'] == '40% off') { $salePrice = $thePrice * 0.6; }
                else if($field2['discount'] == '25% off') { $salePrice = $thePrice * 0.75; }
                // add the coupon code to the array of coupons available for use
                array_push($coupon_use, $field2['couponCode']);
                // display the prices
                echo 'ITEM #'.$i.'<br><s>$'.$thePrice.'</s><br>$'.$salePrice.'<br><br>';
            }
        }
    }
    else { echo 'ITEM #'.$i.'$'.$thePrice; }
}

现在您可以将coupon_use数组的值存储到结帐页面。


推荐阅读