jaymc Posted January 20, 2007 Share Posted January 20, 2007 I want to have a query that will query a database for matches of a usernameSo, if i search for 'Jamie' and their are 10 rows where the username is equal to that I will get 10 rows of resultsWell, in each of those rows is another numerica field, What I want to do is added up all of those to give me the totalI 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 nicelyAny ideas? Link to comment https://forums.phpfreaks.com/topic/34939-mysql-fields-total/ Share on other sites More sharing options...
printf Posted January 20, 2007 Share Posted January 20, 2007 [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 More sharing options...
jaymc Posted January 20, 2007 Author Share Posted January 20, 2007 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 https://forums.phpfreaks.com/topic/34939-mysql-fields-total/#findComment-164833 Share on other sites More sharing options...
printf Posted January 20, 2007 Share Posted January 20, 2007 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 More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.