Reputation: 217
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
Reputation: 835
Also it's good practice to test if $result exists or not:
if (!$result) {
die('Invalid query: ' . mysql_error());
}
Upvotes: 0
Reputation: 5213
Something like this?
$result = mysql_query("SELECT SUM(column_name) FROM tablename");
$row = mysql_fetch_assoc($result);
$sum = $result[0];
Upvotes: 0
Reputation: 434
$sql = "Select SUM(ver) AS ver from tablename";
$sum = mysql_query($sql);
$result= mysql_fetch_object($sum);
echo $result->ver;
Upvotes: 0
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
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