Jump to content

How do I add the values of a field from multiple rows with php and mysql?


OmenLW

Recommended Posts

In mysql I have a table with a few fields:

 

Name | Zip | Points

 

OmenLW, 96717, 24

AnotherDude, 89119, 43

SomeChick, 96717, 89

 

How do I grab everyone from a certain zip and add their points together.

 

96717: 113 Points

89119: 43 Points

 

Thanks

Why not just pull all the results from your database that are equal to the your zip and then just add the results of the points in a loop to get them all?

 

thats what I am having trouble with, the code used for adding the results.  I can pull the results through a loop but the adding is where I am having problems.  I do not know the code to use.  I am googling as we speak looking for the answer.

Thanks for the google tips.

 

I found this page ad it taught me what I needed to know.

 

http://www.tizag.com/mysqlTutorial/mysqlsum.php

 

PHP and MySQL Code:

<?php
// Make a MySQL Connection

$query = "SELECT type, SUM(price) FROM products GROUP BY type"; 

$result = mysql_query($query) or die(mysql_error());

// Print out result
while($row = mysql_fetch_array($result)){
echo "Total ". $row['type']. " = $". $row['SUM(price)'];
echo "<br />";
}
?>

 

Display:

Total Clothing = $67.47
Total Food = $8.73
Total Music = $45.53
Total Toy = $93.94 

 

I will leave this here in case anyone else needs the answer.

Why not just pull all the results from your database that are equal to the your zip and then just add the results of the points in a loop to get them all?

 

Because its inefficient. Databases are made for doing exactly what the OP wanted to do (in the way he found in that tutorial). Its better to have the database perform the function then pull that information from the database, than it is to pull it and then process it with php.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.