我想要添加while循环浮点值

时间:2019-04-06 13:25:33

标签: php mysql mysqli

我在PHP中添加浮点值时遇到问题 我已经尝试了很多次,但是我不知道该怎么做。 在我的代码下面。

$selctAllAmount = "SELECT * FROM amount WHERE id = '$id'";


if($resultAmount = mysqli_query($conn, $selctAllAmount)){
    if(mysqli_num_rows($resultAmount) > 0){
        while($row = mysqli_fetch_array($resultAmount)) {
            $AmountAll = $row['amount'];
            $counts = count($AmountAll);
            echo $counts;
        }
    }
}

$ AmountAll变量都有两个float值,例如0.5、0.6、0.9、0.3 我如何计算所有这些值,例如0.5、0.6、0.9、0.3 = 2.3 请帮助我的人,谢谢StackOverFlow

2 个答案:

答案 0 :(得分:1)

遍历结果并将其添加到每次迭代的变量$total中。

此外,在查询中使用变量输入时,请确保使用准备好的语句。

$selctAllAmount = "SELECT amount FROM amount WHERE id = ?";
if($stmt = $conn->prepare($selctAllAmount)) {
    $stmt->bind_param("s", $id);
    $stmt->execute();
    $stmt->bind_result($amount);

    $total = 0;
    while ($stmt->fetch()) {
        $total += $amount;
    }
    $stmt->close();
    echo $total;
}

更好的是,使用SUM()运行单个查询,

$selctAllAmount = "SELECT SUM(amount) as amount FROM amount WHERE id = ?";
if($stmt = $conn->prepare($selctAllAmount)) {
    $stmt->bind_param("s", $id);
    $stmt->execute();
    $stmt->bind_result($amount);
    $stmt->fetch();

    echo $amount;
    $stmt->close();
}

答案 1 :(得分:0)

您必须以这种方式完成

 $AmountAll += $row['amount'];

OR

如果要在SQL查询中执行SUM,请使用SUM,例如

SELECT SUM(amount) As total FROM tablename