POST输入类型="数字"在一个循环内,并将其总和SUM

时间:2017-07-03 15:45:55

标签: php html mysql loops sum

所以我在这个循环中有这个购物车,显示数据库中的产品和价格,每行都有一个输入类型="数字"叫数量。我想要的是:当我点击一个提交按钮或一个名为&#34的href时,继续付款"我希望价格乘以每行的数量,返回totalPrice。

这是我的代码到目前为止,但它不起作用:

$query = "select * from Cart where id = '" . $_SESSION['id'] . "'";
$res=mysqli_query($lig,$query) or die ("error");
$nr=mysqli_num_rows($res);
echo "<table>";
for($i=0;$i<$nr;$i++) { 
    echo "<tr>";
    $row=mysqli_fetch_assoc($res);
    echo "Product: " . $row['product'];
    echo "Price: " . $row['price'];
    Quantity: &nbsp <input type="number" name="quantity"
    $quantity += $quantity + $_POST['quantity'];
    echo "</tr>";
}
<a href="confirmPayment.php?quantity=<?php echo $quantity;?>

1 个答案:

答案 0 :(得分:0)

如果其他人正在搜索并希望至少就如何获得价格*数量的小计以及所有商品的总数而得到答案,这对我有用:

<?php 

    $query = "select * from Cart where id = '" . $_SESSION['id'] . "'";
    $res = mysqli_query($lig,$query) or die ("error");
    $total = 0;
    echo "<table><tr><th>Product:</th><th>Price:</th><th>Quantity:</th><th>Subtotal:</th></tr>";
    while($row = mysqli_fetch_assoc($res)) { 
        $subtotal = $row['quantity'] * $row['price'];
        echo "<tr>";
        echo "<td>" . $row['product'] . "</td>";
        echo "<td>" . $row['price'] . "</td>";
        echo "<td>" . "<input type='number' min='0' name='quantity' value='" . $row['quantity'] . "'></td>";
        echo "<td>" . $subtotal . "</td>";
        echo "</tr>";
        $total = $total + $subtotal;
    }
    echo "</table>";
    echo "<a href='confirmPayment.php?quantity=" .$total ."'>Confirm pay " . $total ."</a>";

?>

基本上,我所做的只是初始化Total,在循环内创建一个小计,并将该小计添加到Total。它也看起来有点干净。我的输出如下:

Picture of my version running...