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
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
Share on other sites

I'll give that a try, althought, I followed a tutorial which gave me this line and it gives an error saying SUM() is not a function

$query = "SELECT type, SUM(price) FROM products GROUP BY type";

Any idea their just to clear it up?
Link to comment
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
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.