Forum Moderators: coopster

Message Too Old, No Replies

Outputting a Sum

Newbie needs help!

         

irishcocacola

7:13 pm on Jul 12, 2007 (gmt 0)

10+ Year Member



Howdy Folks,

A newbie to MySQL and PHP both. I'm trying to output the sum of a column.

Here is the code I have.

<?
$query2="SELECT Sum(num) FROM tbl_secrets";
$totalviews = mysql_query($query2);
echo $totalviews;
?>

The output I get is:
Resource id #6

I've tried everything. I got so angry I just got up and left, because I knew I would have started hitting my computer...or someone else.

So, I tried mysql_fetch_array, and mysql_fetch_assoc. Neither worked.
Can someone help me calm my nerves?

eelixduppy

7:16 pm on Jul 12, 2007 (gmt 0)



Hello, and Welcome to WebmasterWorld!

Try something like this:


$query2="SELECT SUM(num) AS `totalviews` FROM `tbl_secrets`";
$result = mysql_query($query2);
$row = mysql_fetch_assoc($result);
echo $row['totalviews'];

You were trying to echo out the resource variable, but that doesn't contain the data how you want. You must use a function like mysql_fetch_assoc to get the data correctly and echo it to the browser.

irishcocacola

7:22 pm on Jul 12, 2007 (gmt 0)

10+ Year Member



You have no idea how much happier...and calmer my nerves are!

I feel so much better now, you've really made my day!

BUT

Can someone explain what the mysql_fetch_assoc function does...

And why do you have to specify $row['totalviews']?

I was under the impression that you only use a variable followed by ['VAR'] when referring to the X and Y coordinates in a MySQL table (as in: X['Y'].

Thank you!

eelixduppy

7:28 pm on Jul 12, 2007 (gmt 0)



The first place to look for info on the function is the documentation: [php.net...]

What this function does is uses the result from mysql_query() to retrieve a row from a mysql table in the form of an array [php.net]. So, we use mysql_fetch_assoc to retrieve the array for that first row (there is only one row for this query) and echo the appropriate array value.

irishcocacola

7:34 pm on Jul 12, 2007 (gmt 0)

10+ Year Member



So the query is creating a 1 x 1 table/array?

I'll look into that reference now.