views:

53

answers:

2

I am pulling a set of numbers from a MySQL database and am trying to do some simple math on them to calculate a total price to put into an invoice, but PHP isn't cooperating. I thought it might be a type-coercion issue, so I tried adding some intval and floatval calls, but still the total always comes out to 0.

Here is the relevant code.

$totalSum = 0;
$parts = $db->select("*", "WHERE record_id=$id", "recordparts");

    foreach($parts as &$part) {
        $part['priceTotal'] = (floatval($part['price']) * intval($price['quantity'])) + (floatval($part['laborTime']) * floatval($price['laborRate']));
        $totalSum += $part['priceTotal'];
    }

    $record['parts'] = $parts;
    $record['partsSum'] = $totalSum;

And here are the results of the above operation

parts => Array (1)
  0 => Array (8)
    id => "18"
    partNumber => "92-000001"
    record_id => "17"
    price => "11.5"
    laborTime => "2"
    laborRate => "65"
    quantity => "1"
    priceTotal => 0
partsSum => 0
+1  A: 

Wow, after looking at it, it was just a typo (well, two). For whatever reason I randomly switch from using $parts to using $price as the array. Fixing that fixed my problem.

foreach($parts as &$part) {
        $price = floatval($part['price']);
        $quantity = intval($part['quantity']);
        $laborTime = floatval($part['laborTime']);
        $laborRate = floatval($part['laborRate']);

        $part['priceTotal'] = ($price * $quantity) + ($laborTime * $laborRate);
        $totalSum += $part['priceTotal'];
}
tj111
I just found this. Yes, that was the problem.
zombat
+1  A: 

Out of curiosity, why don't you just let MySQL do the multiplication? I'm guessing this will be faster anyway.

$totalSum = 0;
$parts = $db->select("*, price * quantity AS priceTotal", "WHERE record_id = $id", "recordparts");

foreach($parts as &$part) {
    $totalSum += $part['priceTotal'];
}

$record['parts'] = $parts;
$record['partsSum'] = $totalSum;
Jordan
I could do it all in SQL, but I already need all the individual numbers for display purposes and had to loop through them anyway for the total sum, and I just find it clearer to read the math in PHP than in SQL.
tj111