简体   繁体   中英

Cart Total with Shipping

I have been trying to find out the total price based on the product quantity, I am saving quantity and price in database following is the query that i am using to find out the total price

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

SELECT id
FROM users
WHERE email =  'test'
)

Now what i want , i need add shipping charges, if the quantity is 1-5 than shipping charges would be 50 and if 6-10 than it would be 100 ad so on

How can i achieve this ? this is what i am trying but wrong! Please find me a solution.

 $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);
}

You could use CASE statement instead

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<<<

Try below code, You need to add shipping charge into subtotal

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

EDIT

if you want to increase shipping charge on every 5+ qty. try below code

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

EDIT You can achieve this using sql query also :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM