Forum Moderators: coopster
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?
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.
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!
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.