【问题标题】:Count total price of items with php用php计算物品的总价格
【发布时间】:2016-07-09 22:34:48
【问题描述】:

我创建一个简单的 php 购物车:

  • 按数量添加产品。
  • 更新产品数量。

我想计算购物车中所有商品的总价,但不知道如何计算?

我用这个代码显示项目:

<?php
session_start();
$where = implode(",",$_SESSION['product']);
    $get_p = $mysqli->prepare("select id,name,price,imgs,quantity from products where id IN ($where)");
    $get_p->execute();
    $get_p->bind_result($id,$name,$price,$imgs,$quantity);
    $get_p->store_result();
    while($get_p->fetch()) {
    $qty = $_SESSION["qty"][$id];
    $total = $qty * $price;
?>
<tr>
<td><img src="<?php echo htmlspecialchars($imgs);  ?>"/></td>
<td><?php echo htmlspecialchars($name);  ?></td>
<td><?php echo htmlspecialchars($price)."×".$qty;  ?></td>
<td><input type="number" value="<?php echo $qty; ?>"  min="1" name="qty_cart"></td>
<td><input type="submit" value="delete" name="delete<?php echo $id; ?>"/></td>
<?php
if(isset($_POST["delete".$id])) {
unset($_SESSION['product'][$id]);
}
?>
</tr>
<?php
}

?>
</table>
<div class="price_all_items">
</div>
<input type="submit" name="sub" value=""/>
</form>

【问题讨论】:

  • 您错误地使用了准备好的语句。 select sum(price) where id = ?
  • 你的意思是我错误地使用了准备好的语句。
  • select sum(price) 这只是获取商品的价格,但我想要商品的总价格多个数量
  • @Mouradkaroudi 你没有使用准备工作。你可以只使用 $mysqli_query
  • 您需要为实际值使用占位符。 php.net/manual/en/mysqli.quickstart.prepared-statements.php 然后绑定它们。将数量乘以价格。

标签: php mysql


【解决方案1】:

替换这部分代码

while($get_p->fetch()) {
    $qty = $_SESSION["qty"][$id];
    $total = $qty * $price;

有了这个

$totalSum = 0;
while($get_p->fetch()) {
    $qty = $_SESSION["qty"][$id];
    $total = $qty * $price;
    $totalSum += $total;

在您结束循环后,$total 中的值将具有总量。

【讨论】:

  • 没有人,这个代码只是得到一件商品的总价我想要得到购物车中所有商品的总价
  • 所以我没有正确理解您的查询。再次检查我的答案。
  • 否 :D 看我有 iphone [价格:199,数量:2]。我有 Ipad [价格:200,数量:3]。 iphone的总价是:398 ipad的总价是:600我要变量显示这两个项目的总价:998
  • 再看看我的建议 - 在你的 $total value 循环之后,你将拥有你需要的东西。看看有 += 所以 $total 将增加 $qty * $price 对于您的 while 循环中的每个产品。以您的示例为例:$total = 0,然后 $total = $total + 199 * 2 (之后您在 $total 中有 398),然后对于下一个产品,您将再次获得 $total = $total + 200 * 3 (所以$total 将等于 398 + 600)。如果你说不正确,我的回答有什么问题?
  • 您的代码是显示每个产品的总价我要计算所有价格*它们的数量
猜你喜欢
  • 2021-09-07
  • 1970-01-01
  • 2021-04-17
  • 2013-02-12
  • 2021-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-10
相关资源
最近更新 更多