简体   繁体   中英

How to calculate total price in php

I am getting the price of the product from db using the product id i have stored in php array.

i have a php function where in i want to hold a total of all the products purchased. here i am getting the cart items and i am calling the function which should hold total amount. i am passing the value price each time when i retrieve the product from cart.

for example for first item iteration i send value 300, and for second 400, for third 900.

i want to add up all these and get total price of 1600 in payableAmount() how can i do this?

function getCartitems($product_id){
    $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } 
    $sql = "SELECT product_id,product_name,product_price,product_image_url FROM product_list WHERE product_id='$product_id'";
    $result = $conn->query($sql);      
    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {              
        echo "<tr><td><img class='cart-image img-responsive' src='".$row["product_image_url"]."'></td><td>".$row["product_name"]."</td><td><b>&#8377; </b>".floor($row["product_price"])."</td><td><a href='mycart.php?action=remove&product_id=".$row['product_id']."'><span class='glyphicon glyphicon-remove'></span> remove</a></td></tr>";
        $price = $row['product_price'];
        payableAmount($price);      
        }
    } else {
        echo "There are no such items";
    }   
    $conn->close();
}

function payableAmount($totalPrice){    
   // calculate total price here
    $total = $totalPrice;
    echo $total;
}

You just simply update your query instead like as

$total_price = 0;
while($row = $result->fetch_assoc()) {              
  echo "<tr><td><img class='cart-image img-responsive' src='".$row["product_image_url"]."'></td><td>".$row["product_name"]."</td><td><b>&#8377; </b>".floor($row["product_price"])."</td><td><a href='mycart.php?action=remove&product_id=".$row['product_id']."'><span class='glyphicon glyphicon-remove'></span> remove</a></td></tr>";
  $total_price += $row['product_price'];
}

Just declare total outside -

 $total =0;
function payableAmount($totalPrice){    
   // calculate total price here
   global $total;
    $total += $totalPrice;
    echo $total;
}

Use the while loop to calculate the price. Declare a variable $totalPrice and then sum it within the while loop.

function getCartitems($product_id){
    $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } 
    $sql = "SELECT product_id,product_name,product_price,product_image_url FROM product_list WHERE product_id='$product_id'";
    $result = $conn->query($sql);      
    if ($result->num_rows > 0) {
        $totalPrice = 0;
        while($row = $result->fetch_assoc()) {              
        echo "<tr><td><img class='cart-image img-responsive' src='".$row["product_image_url"]."'></td><td>".$row["product_name"]."</td><td><b>&#8377; </b>".floor($row["product_price"])."</td><td><a href='mycart.php?action=remove&product_id=".$row['product_id']."'><span class='glyphicon glyphicon-remove'></span> remove</a></td></tr>";
        $price = $row['product_price'];
        $totalPrice += $price;      
        }
    } else {
        echo "There are no such items";
    }   
    $conn->close();
}

Create a Variable outside the function. Then you add the price to this variable in the funtion. and use

$total += $totalprice.

you can simply add the price in loop and get the same by storing it in variable.

payableAmount($price);//Not Need to call different function as it return only the current price,instead of this you can add the price as given below $total_price+=$price;

You need simple modification in your payableAmount() function

function payableAmount(&$totalPrice){    
  // calculate total price here
   $totalPrice += $totalPrice;
}

Variable is passed now via reference so it will be modified after you do it you can echo $totalPrice and it will be changed, the other 2 options is to use static variable or global. However if I were you I wouldn't use function for such a simply task. Just declare $total before loop and inside loop $total += $price; and it is enough

    if ($result->num_rows > 0) {
        $totalPrice = 0; // Initialice the var before to go into the while loop
        while($row = $result->fetch_assoc()) {              
            echo "<tr>
                <td><img class='cart-image img-responsive' src='".$row["product_image_url"]."'></td>
                <td>".$row["product_name"]."</td><td><b>&#8377; </b>".floor($row["product_price"])."</td>
                <td><a href='mycart.php?action=remove&product_id=".$row['product_id']."'>
                    <span class='glyphicon glyphicon-remove'></span> remove</a></td>
                </tr>";
            // increment the price...
            $totalPrice += $row['product_price'];
        }
        // Now you can use the $totalPrice var
    } else {
        echo "There are no such items";
    }   

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