Page 1 of 1
Adding Up SQL Columns[solved]
Posted: Sun Oct 23, 2011 4:44 pm
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];
}}
Re: Adding Up SQL Columns
Posted: Sun Oct 23, 2011 5:34 pm
by Jackolantern
You can do this right in the query!
Here is a tutorial explaining how

Re: Adding Up SQL Columns
Posted: Sun Oct 23, 2011 5:59 pm
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)'];
}
Re: Adding Up SQL Columns
Posted: Sun Oct 23, 2011 6:55 pm
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.
Re: Adding Up SQL Columns[solved]
Posted: Mon Oct 24, 2011 4:37 pm
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.