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

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.