0

I'm making a shopping cart using PHP and MySQL . I'm trying to calculate the total price by multiplying item price and item quantity on each row and then adding it to total price . I honestly tried many different ways but none of them worked. I thought about doing that in JavaScript , but I've been told that it makes my code vulnerable . In JavaScript , it's as simple as total += (quantity * price). So how do I go about doing that in PHP and MySQL ?

I'm a beginner in PHP and MySQL and also i will be using prepared statements later to prevent SQL injections. I just want to get the totalprice to work properly first.

Thank you

 <table>
            <tr>

                <th>ITEM</th>
                <th>MODEL</th>
                <th>QUANTITY</th>
                <th>COLOR</th>
                <th>PRICE</th>
            </tr>
            <?php
            $conn = mysqli_connect(
                "localhost",
                "user",
                "password",
                "db"
            );
            // Check connection
            if ($conn->connect_error) {
                die("Connection failed: " . $conn->connect_error);
            }
            $sql = "SELECT productname, productmodel, productquantity,
                    productcolor, productprice, id FROM posts";
            $result = $conn->query($sql);
            if ($result->num_rows > 0) {
                // output data of each row
                while ($row = $result->fetch_assoc()) {
                    echo "<tr><td>" . $row["productname"] . "</td><td>" .
                        $row["productmodel"] . "</td><td>"
                        . $row["productquantity"] . "</td><td>" .
                        $row["productcolor"] . "</td><td>"
                        . "$" . $row["productprice"] . "</td><td>" . "<a href='delete.php?id=" . $row['id'] . "'>REMOVE</a>" . "</td></tr>";
                }
                echo "</table>";

            } else {
                echo "0 results";
            }

            ?>

        </table>


        <h2 id="cart-total-price-title">TOTAL:</h2>
        <h2 id="cart-total-price">$0.00</h2>

Thatdude22
  • 57
  • 9

1 Answers1

1

I would define a cart total variable outside of your while loop, and then in every instance of the while loop, add the current product's price multiplied by it's quantity.

<?php
$cartTotal = 0;
while ($row = $result->fetch_assoc()) {
  $cartTotal = $cartTotal + ($row["productprice"] + $row["productquantity"]);
} 
?>
<h2 id="cart-total-price">$<?php echo $cartTotal ?></h2>

There's a shorthand for incrementing variables too which would clean it up a bit.

$cartTotal += ($row["productprice"] + $row["productquantity"]);