显示优惠券

时间:2018-05-04 06:35:15

标签: php mysql

所以我有这个MySQL表,其中一个项目有一个名为isCoupon的字段。如果卖家未将该项目用于优惠券使用,则默认设置为0。每个项目按ID排序,在商店中,可以有多个优惠券,其中该项目也可以打折。但是,如何在项目包含时显示优惠券?如何让买家选择使用哪张优惠券?如果我把" 50%的折扣"以及如何计算新价格呢?记录而不是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

谢谢!

1 个答案:

答案 0 :(得分:0)

尝试以下方法。至于买家选择哪个优惠券,您应该先让买家选择该项目,然后选择优惠券进入结账页面。

$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数组的值存储到结帐页面。