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



我正在使用PHP和MySQL制作购物车。我正在尝试通过将每行上的项目价格和项目数量相乘,然后将其添加到总价来计算总价。老实说,我尝试了许多不同的方法,但没有一种奏效。我想过在 JavaScript 中这样做,但有人告诉我它使我的代码容易受到攻击。在 JavaScript 中,它就像总 +=(数量 * 价格(一样简单。那么我该如何在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"]);

相关内容

最新更新