0

How would i add the sum of a column in mysql?

Here's my code:

$add = mysql_query("SELECT SUM(rsvp) FROM TABLE_NAME WHERE rsvp > 0;")or die(mysql_error());

when i echo it, it gives me a Resource id #

6 Answers 6

2

try this instead

$q = mysql_query("SELECT SUM(rsvp) as sum FROM TABLE_NAME WHERE rsvp > 0") or die(mysql_error());
$row = mysql_fetch_assoc($q);
echo $row['sum'];

I recommend looking up more on how to use PHP and MySQL together possibly from one of these sites: - http://php.net/manual/en/book.mysql.php - http://www.youtube.com/user/phpacademy - this one is pretty nooby but it does cover everything from pagination to image uploads and beyond. a good place to start I guess.

Sign up to request clarification or add additional context in comments.

5 Comments

I wouldn't recomment naming the column 'sum' since it is a keyword as well. Also, www.php.net is a fine resource for finding information about PHP and MySQL.
W3Schools yikes no! Have them read the official PHP docs instead! us.php.net/manual/en/book.mysql.php
yeah i don't know why I didn't say that :-(
@kylestevenson: You can edit your answer and add any more info you think may be useful.
There you go, hope that helps more
1

mysql_query returns a resource, not a value. You need to use another function, such as mysql_fetch_row to access the value it contained:

$result = mysql_query("SELECT SUM(rsvp) FROM TABLE_NAME WHERE rsvp > 0;") or die(mysql_error());
$row = mysql_fetch_row($result); // get an array containing the value of the first row of the above query
$sum = (int) $row[0]; // get an integer containing the value of the first (and, here, only) item in that row

Comments

0

Yes, and you use mysql_fetch_array to fetch a row from that resource.

$resource = mysql_query( ... );
if ($row = mysql_fetch_array($resource))
{
  $add = $row[0];
}

Comments

0

I've found the problem,

Note: Undefined index: sum in D:\xampp\htdocs\demo-shop\cart.php on line 9

$sum_query= "SELECT sum(Prod_Tot) as sum FROM cart WHERE Prod_Tot > 0"; 
$sum_query_res  = mysql_query($sum_query);
$row = mysql_fetch_row($sum_query_res);
echo $row['sum'];

If I put echo $row['0']; instead of echo $row['sum']; then it is ok.

1 Comment

Try $sum_query= "SELECT sum(Prod_Tot) as 'sum' FROM cart WHERE Prod_Tot > 0";
0

ended up figuring it out.

$add = mysql_query("SELECT SUM(rsvp) FROM TABLE_NAME WHERE rsvp >= 1;")or die(mysql_error());
list ( $rsvp_total ) = mysql_fetch_array($add); 

echo $rsvp_total;

Comments

0

This is short and simple try it

$sql = mysql_query("SELECT SUM(rsvp) as sum FROM TABLE_NAME WHERE rsvp > 0") or die(mysql_error());

$record = mysql_fetch_assoc($sql); echo $record['sum'];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.