SQL summing a product column

I want to find the sum of an SQL column which is generated by being the product of two other columns. The only point of the column is to find this summed value. What is the best way of doing this? My thoughts on options were: 1. Generating the column automatically with mySQL, 2. Generating the column with php in mySQL, 3. Not generating a column and only generating the sum value in php.

Option 3, but generated from the database not php.

[php]SELECT sum(col1 + col2 + col3 ) as total from table[/php]

So I can get this to work from within PHPMyAdmin using:

SELECT SUM(column1 * column2) from table

I can’t get this to work from PHP using the code below, which is returning “Resource id #8”, which suggests to me that mysql_query is the wrong thing to use here. What’s wrong with the code below?

$query = “SELECT SUM(column1 * column2) from table”;
echo $result = mysql_query($query);

For one, you shouldn’t be using mysql_

I’m well aware of that, but I’m learning PHP through older tutorials which use mysql. Seeing as this is the last bit of PHP I need to fix on this mini-project I was hoping to just get things working before converting it all to PDO.

It never ends up happening like that, I can assure you ;D

result returns an array.

[php]while ($row = mysql_fetch_assoc($result)) {
echo $row[‘column_name’];
}[/php]

Thanks for the reply but I’m still struggling to make sense of this! :frowning:

I think I already tried your new addition to the code before by adding this after the $result row (without the echo), but I couldn’t understand what value to use for ‘column name’ as there is no column? I have two columns multiplied together and an ‘imaginary’ summed column. I wasn’t sure if this was the correct route to take so I went back to basics.

This gives an alias for the column making it accessible with ‘total’ as the column name.

Swish!! ;D
Yeah that’ll do it - I’ve seen this topic in a few places where only the MySQL part is displayed and not all the methods included “as total”. As I wasn’t using it up until now I took it out and forgot about it.

Next dilemma - do I learn the PDO way of doing things or should I continue watching an anime about garbage haulers in space…

Thanks very much!

Sponsor our Newsletter | Privacy Policy | Terms of Service