Morgan Green
Morgan Green

Reputation: 996

Sum of Foreach Loop

I'm trying to total a bill balance with a program I'm working on in PHP. The code I use to pull the pricing is as such.

        public function PackagePricing($arg) {
            $query = <<<SQL
            SELECT packageID
            FROM customer_packages
            WHERE active = :true
            AND customerID = :arg
SQL;
            $resource = $this->db->db->prepare( $query );
                $resource->execute( array (
                ":true" => 1,
                ":arg"  => 1,
                ));
                foreach($resource as $row) {
                    self::GetPricing($row['packageID']);
                }
        }
        public function GetPricing($arg) {
            $query = <<<SQL
            SELECT price
            FROM products
            WHERE id = :arg
SQL;
            $resource = $this->db->db->prepare( $query );
                $resource->execute( array (
                ":arg"  => $arg,
                ));
                $totalBill = 0;
                foreach($resource as $row) {
                        $totalBill+= $row['price'];
                }
                echo $totalBill;

        }

Now by my understanding this should work, but what I'm getting in turn is: enter image description here

On the right you can see the billing total and rather than totaling out it's giving me each individually.

Upvotes: 0

Views: 79

Answers (1)

user2302957
user2302957

Reputation:

The error seems quite obvious. Here's your sequence in different words :

  1. Get all packages ID.
  2. Foreach package ID, get the price of the item (only one result is returned)
  3. For that single result, add up all the prices (you only get one). Print it and go back to 2.

What you see is not 2 prices that have been added as strings in some sort of way. You simply prints subsequently 2 different prices. 10 & 30

GetPricing should return a price, and the foreach loop that calls it should make the sum.

$total = 0;
foreach($resource as $row) 
{
    $total += self::GetPricing($row['packageID']);
}

Hope this helps.

Upvotes: 1

Related Questions