Page 1 of 1

Mysql Math Problem

Posted: Sun Jul 18, 2004 10:45 am
by bdeonline
Ok here is what I have

A 2 mysql columns with money values with quantities:
atest / btest
5.00 / 2
5.50 /5

I want to be able to
times atest row 1 with btest row 1
times atest row 2 with btest row 2
and so on then add a total

Code: Select all

$query = "SELECT * FROM test";
  $countRows = $db_mysql->query($query);

while ($countRow = mysql_fetch_array($countRows, MYSQL_ASSOC)) {
    $total = $countRowї'atest'] * $countRowї'btest'] . " ";
    $total2 = explode(" ", $total);
}
    echo array_sum($total2);
So what I have been trying is taking the data from the db into two arrays times them and then adding the sum but after the data is retrieved it chages it into a string so I changed it back into a array but it still isn't working right.

Posted: Sun Jul 18, 2004 11:06 am
by JAM
Perhaps the following might be of interest. Not the solution perhaps, but some ideas of what can be done:

Code: Select all

$res = mysql_query("select cost, quantity, cost * quantity as total from test");
    while ($row = mysql_fetch_assoc($res)) {
        echo "<pre>
            Cost: {$row['cost']}
            Quantity: {$row['quantity']}
            Grand total: {$row['total']}
        \n";
    }
Result:

Code: Select all

Cost: 5.00
            Quantity: 10
            Grand total: 50.00
        

            Cost: 2.00
            Quantity: 255
            Grand total: 510.00
I'm letting the database itself deal with the math, instead of trying to re-invent the wheel again using php. Might just work for you also.

Posted: Sun Jul 18, 2004 11:11 am
by feyd

Code: Select all

<?php

$query = "SELECT (`atest` * `btest`) AS `product` FROM `test`";
$res = $db_mysql->query($query);

$result = array();
while($row = mysql_fetch_assoc($res))
  $result[] = $row['product'];
}

echo array_sum($result);

?>

Posted: Sun Jul 18, 2004 11:53 am
by bdeonline
That worked just as I needed thanks.