繁体   English   中英

我如何使用 PHP 和 MySQL 设置购物车的总价

[英]How do i set up total price for shopping cart using PHP and MySQL

我正在使用 PHP 和 MySQL 制作购物车。 我试图通过将每行的商品价格和商品数量相乘,然后将其添加到总价来计算总价。 老实说,我尝试了许多不同的方法,但没有一个奏效。 我想在 JavaScript 中这样做,但有人告诉我这会使我的代码容易受到攻击。 在 JavaScript 中,它就像 total += (quantity * price) 一样简单。 那么我该如何在 PHP 和 MySQL 中做到这一点呢?

我是 PHP 和 MySQL 的初学者,稍后我将使用准备好的语句来防止 SQL 注入。 我只想先让总价正常工作。

谢谢

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

我会在 while 循环之外定义一个购物车总变量,然后在 while 循环的每个实例中,添加当前产品的价格乘以它的数量。

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

增加变量也有一个简写,可以稍微清理一下。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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