计算连续金额的总和

Calculating sum of amounts in a row

我需要帮助,通过搜索 Google 找到了这里。但是卡住了,找不到合适的示例来完成我的脚本。

一个简单的 Intranet 股票价值系统。 我只需要计算股票价值行。

见下图红色方块

我的代码 - 我如何使用我的脚本计算值..或我可以查看的任何其他示例(链接在这里或在网络上) - 非常感谢....

        <?php try {
        $conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
        $conn->exec("SET CHARACTER SET utf8");// Sets encoding UTF-8
        $sql = "select * from stock_dry where stock_cat_id = 14 order by stock_id" ;
        $result = $conn->query($sql);
        if($result !== false) {
        $cols = $result->columnCount();
        foreach($result as $row) {
    ?>
    <tr>
    <td class="text-left"><?php echo $row['stock_id'];?></td>
    <td class="text-left"><?php echo $row['stock_name'];?></td>
    <td class="text-left"><?php echo $row['stock_count'];?></td>
    <td class="text-left"><?php echo $row['stock_price'];?></td>
    <td class="text-left">
    <?php 
        $sum_total = $row['stock_count'] * $row['stock_price'];
        echo $sum_total;
    ?>
    </td>
    <td class="text-left"><?php echo $row['stock_cat'];?></td>
    </tr>
    <?php
        } } $conn = null; }
        catch(PDOException $e) {
        echo $e->getMessage();}
    ?>

您可以简单地在循环之前添加一个变量,例如:

$tot = 0;

然后在 sum_total 计算后添加:

$tot += $sum_total;

我也会对 sum_total 做一点改动(如果你使用整数):

$sum_total = intval( $row['stock_count'] ) * intval( $row['stock_price'] );

或(如果您使用浮点数):

$sum_total = floatval( $row['stock_count'] ) * floatval( $row['stock_price'] );

还有:

echo number_format( $sum_total, 2 );

您可以打印带 2 位小数的浮点数。