cbarlow123
cbarlow123

Reputation: 217

Sum the total of a column and save as a variable

Trying to sum the total of a column and save as a variable. The query has worked as I have tested it with PHPMyAdmin. Just struggling to save the figure received from the query into a variable.

 $con = mysql_connect(DB_HOST, DB_USER, DB_PASS);
 if (!$con)
   {
   die('Could not connect: ' . mysql_error());
   }

 mysql_select_db(DB_NAME, $con);

 $result = mysql_query("SELECT SUM(column_name) FROM tablename");



  mysql_close($con);  

Any help would be much appreciated.

Thanks!

Upvotes: 0

Views: 4311

Answers (5)

Silviu
Silviu

Reputation: 835

Also it's good practice to test if $result exists or not:

if (!$result) {
    die('Invalid query: ' . mysql_error());
}

Upvotes: 0

Manish
Manish

Reputation: 5213

Something like this?

$result = mysql_query("SELECT SUM(column_name) FROM tablename");
$row = mysql_fetch_assoc($result);
$sum = $result[0];

Upvotes: 0

Daxcode
Daxcode

Reputation: 434

$sql = "Select SUM(ver) AS ver from tablename";
$sum = mysql_query($sql);
$result= mysql_fetch_object($sum);
echo $result->ver;

Upvotes: 0

Gustavo Vargas
Gustavo Vargas

Reputation: 2597

Try this:

$result = mysql_query("SELECT SUM(column_name) as soma FROM tablename");

$row= mysql_fetch_array($result);

$sum= $row['soma'];

Upvotes: 1

nickb
nickb

Reputation: 59709

I believe something like this will work:

$result = mysql_query("SELECT SUM(column_name) as thesum FROM tablename");
$sum = mysql_result( $result, 0, "thesum");

Or even this should work:

$sum = mysql_result( $result, 0);

Upvotes: 0

Related Questions