Cavemanharris
Cavemanharris

Reputation: 183

Calculating sum of amounts in a row

I need help, have managed to get here with searching Google.. but stuck and cannot find a decent sample to complete my script.

A simple stock value system for intranet. All i need is to calculate the Stock Value Row.

See red block on Image belowenter image description here

My Code - How do I calculate the Value with my script.. or any other example's I can look (links here or on the web) - MANY THANKS....

        <?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();}
    ?>

Upvotes: 0

Views: 3047

Answers (1)

Mat
Mat

Reputation: 2184

You can simply add a variable before the loop like:

$tot = 0;

Then after the sum_total calc you add:

$tot += $sum_total;

I also would do a little change to sum_total (if you work with integers):

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

or (if you work with floats):

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

And with:

echo number_format( $sum_total, 2 );

You can print the float with 2 decimals.

Upvotes: 1

Related Questions