购物车总额包邮

时间:2017-10-01 04:46:38

标签: php mysql

我一直试图根据产品数量找出总价, 我在数据库中保存数量和价格以下是我用来查找总价格的查询

SELECT SUM( price * quantity ) AS subtotal, SUM( quantity ) AS qty
FROM  `cart` 
WHERE user
IN (

SELECT id
FROM users
WHERE email =  'test'
)

现在我想要的是,我需要添加运费,如果数量是1-5,那么运费将是50,如果是6-10,那么将是100个广告所以

我怎样才能做到这一点?这是我在尝试但错误的!请找我解决方案。

 $subtotalquery=" SELECT SUM( price * quantity ) as subtotal, SUM(quantity) as qty FROM  `cart` WHERE user IN  (select id from users where email='$user_check')";
                                $t_con=$conn->query($subtotalquery);
                                $subtotalrow = $t_con->fetch_assoc();

                                $subtotal= $subtotalrow['subtotal'];
                                $qty= $subtotalrow['qty'];
                                if($qty>=5)
                                {
                                    $shipping=50 ;

                                    $ithship=$subtotalrow+($shipping);

                                }else
                                {
                                $shipping=50*2 ;

                                    $ithship=$subtotalrow+($shipping*2);
}

2 个答案:

答案 0 :(得分:1)

您可以使用CASE语句

SELECT SUM(price * quantity) AS subtotal,
SUM(quantity) as quantity, 
CASE 
  WHEN SUM(quantity) <=5 THEN
  50
  WHEN SUM(quantity) BETWEEN 6 AND 10 THEN
  100
  ELSE
  150
  END as ShippingCharge
from  `cart` 
WHERE user
IN 
(
SELECT id
FROM users
WHERE email =  'test'
)

<强> >>>Demo<<<

答案 1 :(得分:0)

尝试下面的代码,您需要将运费添加到小计

if($qty<=5)
{
    $shipping=50 ;
}else
{
$shipping=50*2 ;
}
$ithship=$subtotal+$shipping; // add to  subtotal

修改

如果你想增加每5+数量的运费。尝试以下代码

$qty= $subtotalrow['qty'];
$incr  = ceil($qty/5);
$shipping = $incr*50;
echo $shipping;

修改 您也可以使用sql查询来实现此目的:

SELECT SUM( price * quantity ) as subtotal, SUM(quantity) as qty, ((ceil(SUM(quantity)/5))*50) as ShippingCharge FROM  `cart` WHERE user IN  (select id from users where email='$user_check');

DEMO