Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 139
  • Last Modified:

PHP Sum Column in Table

Can anyone tell me how to sum a column in a table?

I have a table named 'charges' with 2 records.  Record 1 'item_price' is 20.  Record 2 'item_price' is 290.  

I tried this code:

 $qry_charges = $dbh->query("SELECT SUM(item_price) as total_price FROM charges");
			$row = $qry_charges->fetch(PDO::FETCH_ASSOC);
			var_export($row);

Open in new window

and got: array ( 'total_price' => '20', )

Then this code:
	    foreach($qry_counts->query("SELECT SUM(item_price) FROM charges") as $row_sum){
		$totals = $row_sum[0];
		echo $totals;

Open in new window

and got: 20

It's always just getting the first record.  Any ideas on why are appreciated.

Thanks,

Steve
0
stkoontz
Asked:
stkoontz
1 Solution
 
Ray PaseurCommented:
This is a data-dependent problem and we don't have the data.  But your first example looks like the queries I have used for this sort of thing.  Can you please do this for us... Make a SELECT query to get all row values for item_price and print out all the rows.  Please post them in the code snippet here, thanks.
0
 
Julian HansenCommented:
The query looks correct - can we see your data.
0
 
stkoontzAuthor Commented:
It was a data problem.  I use Navicat on my local computer to work with the database on my remote server.  When I started up Navicat this morning and opened the table, the second record's item_price was blank.  Navicat must  not have been updating the remote database.

Thanks for the quick help.  I appreciate it.

Steve
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now