Jump to content

MYSQL fields total


jaymc

Recommended Posts

I want to have a query that will query a database for matches of a username

So, if i search for 'Jamie' and their are 10 rows where the username is equal to that I will get 10 rows of results

Well, in each of those rows is another numerica field, What I want to do is added up all of those to give me the total

I have a PHP alternitive which is to use a loop and add them all up one by one but Im sure MYSQL can do it nicely

Any ideas?
Link to comment
https://forums.phpfreaks.com/topic/34939-mysql-fields-total/
Share on other sites

[code]
// db connect, select here...

$query = mysql_query ( "SELECT SUM(numeric_field_name) AS total FROM your_table WHERE username = 'name_to_match';" );
$result = mysql_fetch_assoc ( $query );

echo $result['total'];[/code]

Where as...

numeric_field_name = would be changed to the name of the field you want to add up!
your_table = would be changed to the table name the query will be run on!
name_to_match = would be changed to the username you want to run the query on (IE: Jamie)

printf
Link to comment
https://forums.phpfreaks.com/topic/34939-mysql-fields-total/#findComment-164817
Share on other sites

When you return the result, are you enclosing the [b]SUM(price)[/b] with quotes, so PHP doesn't think your calling a function!


Are you doing this...

[code]echo $row[SUM(price)]; // php fatal error = Call to undefined function SUM() in ...[/code]

If you are, you need to enclose the [b]SUM(price)[/b] with quotes so PHP doesn't think it's a function call.
[code]
<?

$row = array ( 'SUM(b)' => 1 );

echo $row['SUM(b)']; // prints 1, PHP will not try to parse it, because it enclosed with single quotes, you can use double quotes too!

?>[/code]


printf
Link to comment
https://forums.phpfreaks.com/topic/34939-mysql-fields-total/#findComment-164841
Share on other sites

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.