echo SUM

I am trying to connect to a mySQL dB and echo on a page total number of users (live) on our website. Can anyone see what is wrong with this code?
[php]

<?php // Make a MySQL Connection mysql_connect("localhost", "username", "pass") or die(mysql_error()); mysql_select_db("dbname) or die(mysql_error()); // Retrieve the sum of a column $result = mysql_query("SELECT SUM(column) FROM table") or die(mysql_error()); // Print the total on a page echo ("$result"); ?>[/php]

Firstly you’re missing a closing speech mark on mysql_select_db but I’ll put that down to the transferral of your code to the website.

Secondly mysql_query() returns a ‘Result Resource’ rather than a string containing what you’re after. Change that section of code to the following:

[php] // Retrieve the sum of a column
$result = mysql_query(“SELECT SUM(column) AS total FROM table”)
or die(mysql_error());

// Print the total on a page
$result = mysql_fetch_assoc($result);
echo $result[‘total’];[/php]

Thanks a ton! That worked and yes I had copied over wrong.

Do you know the easiest syntax to put some x,xxx formatting into it?

IE: Total Count: 312,121

No worries, expanding from the code posted previously:

[php]// Print the total on a page
$result = mysql_fetch_assoc($result);
$total = number_format($result[‘total’]);
echo $total;[/php]

See more info about the number_format function here.

Sponsor our Newsletter | Privacy Policy | Terms of Service