php - add the amount + price in separate tables

1

Good.

I have the Products table + the Cart table

When I add Add to Cart, the function adds 1 record in the Cart table saying User Name, Product ID, and Quantity of ordered products.

Now I want to add the amount of this products + the price.

function total_price($con) {

    if(isset($_SESSION['u_email'])) {

        $clientID = $_SESSION['u_id'];

        $total = 0;

        $getPriceTotal = "SELECT quantity, product_id FROM public_cart WHERE user_id='$clientID'";
        $run_total = mysqli_query($con, $getPriceTotal);   
        $savedItems = mysqli_fetch_assoc($run_total);

        $quantity = $savedItems['quantity'];
        $productID = $savedItems['product_id'];


        $productQuery = "SELECT product_price FROM public_products WHERE product_id='$productID'";
        $run_product = mysqli_query($con, $productQuery);
        $product_search_price = mysqli_fetch_assoc($run_product);

        while($product_search_price = mysqli_fetch_assoc($run_product)) {

            $product_price = $product_search_price['product_price'];

            $sum = $product_price * $quantity;
            $total += $sum;

        }

         echo number_format($total, 2, '.', '');

    } else {

        echo "0";
    } 

}

But from what I see ... I'm not even able to, because different or super-large values appear ...

The code is simply just counting on a product. Even doing a while.

    
asked by anonymous 15.10.2017 / 23:13

1 answer

0

Your while parts appear incorrectly, considering that you have n records in the public_cart table but each record has only one .

In this way it makes more sense:

function total_price($con) {

    if(isset($_SESSION['u_email'])) {

        $clientID = $_SESSION['u_id'];

        $total = 0;

        $getPriceTotal = "SELECT quantity, product_id FROM public_cart WHERE user_id='$clientID'";
        $run_total = mysqli_query($con, $getPriceTotal);   

        while ($savedItems = mysqli_fetch_assoc($run_total)) {

            $quantity = $savedItems['quantity'];
            $productID = $savedItems['product_id'];

            $productQuery = "SELECT product_price FROM public_products WHERE product_id='$productID'";
            $run_product = mysqli_query($con, $productQuery);
            $product_search_price = mysqli_fetch_assoc($run_product);

            $product_price = $product_search_price['product_price'];

            $sum = $product_price * $quantity;
            $total += $sum;

        }

        echo number_format($total, 2, '.', '');

    } else {

        echo "0";

    }
}
    
16.10.2017 / 14:13