Adding Up SQL Columns[solved]

Place for questions and answers for all newcomers and new coders. This is a free for all forum, no question is too stupid and to noob.
Post Reply
User avatar
MikeD
Posts: 294
Joined: Thu Sep 08, 2011 4:28 am

Adding Up SQL Columns[solved]

Post by MikeD »

Trying to get a characters stats with equipment added.

However I don't know how to add up the numbers from a column.

This is what I have, and it just echo's each equipments speed bonus, it doesn't add them.

$stats= "SELECT * FROM `playerarmor` WHERE `cid`='$cid' AND `equip`='1'";
if ($result1 = mysql_query($stats)){
while ($row2 = mysql_fetch_row($result1)) {
echo $row2[9];
}}
Last edited by MikeD on Sun Oct 23, 2011 9:20 pm, edited 1 time in total.
User avatar
Jackolantern
Posts: 10891
Joined: Wed Jul 01, 2009 11:00 pm

Re: Adding Up SQL Columns

Post by Jackolantern »

You can do this right in the query! Here is a tutorial explaining how :)
The indelible lord of tl;dr
User avatar
MikeD
Posts: 294
Joined: Thu Sep 08, 2011 4:28 am

Re: Adding Up SQL Columns

Post by MikeD »

Thanks, got it right.

However, without doing 10 different queries, how would I change this so I could get the result of 10 columns?

Code: Select all

$query = "SELECT speedadd, SUM(speedadd) FROM `playerarmor` WHERE `cid`='$cid' AND `equip`='1'"; 
	 
$result = mysql_query($query) or die(mysql_error());

// Print out result
while($row = mysql_fetch_array($result)){
	echo $row['SUM(speedadd)'];

}
User avatar
Jackolantern
Posts: 10891
Joined: Wed Jul 01, 2009 11:00 pm

Re: Adding Up SQL Columns

Post by Jackolantern »

Well, I know you can sum multiple columns without additional requirements like this:

Code: Select all

SELECT sum(`speed`) + sum(`speedbonus`) FROM `players`
But I am not exactly sure how you could add the additional sum requirements onto that pattern (like the $cid and equipped requirements). You may have to use subqueries.
The indelible lord of tl;dr
Xaleph
Posts: 897
Joined: Mon Feb 07, 2011 2:55 am

Re: Adding Up SQL Columns[solved]

Post by Xaleph »

hint: remove ALL trailing quotes for your queries, only use single or double quotes ( depending on your PHP string ) for strings in the query. IE: ints, doubles, floats, datetimes et cetera should not carry trailing back or trailing qoutes. Neither should your table name or fields. Why? Because debugging goes a lot faster and it forces you to use good naming conventions for your tables.
Post Reply

Return to “Beginner Help and Support”