cbarlow123
cbarlow123

Reputation: 217

Need to save result as a PHP variable out the result of a MySQL SUM() query

I need to echo the result of my MySQL query, the query works. Just complete mind blank into how to work out how to echo the result of it.

 $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($user_nameid) FROM profits");


 I KNOW SOMETHING GOES HERE BUT WHAT?! ANY HELP?


  mysql_close($con);

Thanks in advance, all help is much appreciated!

Upvotes: 2

Views: 1745

Answers (3)

Marc B
Marc B

Reputation: 360772

Not sure what you're getting at with the query. SUM() applies to a particular FIELD in the table you're querying. Most likely you'd want

SELECT count(*) FROM profits WHERE usernamefield='$username_id';

Note the quotes around the variable. If that variable contains anything that is NOT purely numeric, it must be quoted. And you must also take care of any SQL injection problems:

$username_id = $_POST['username_id'];
$safe_id = mysql_real_escape_string($username_id);
$result = mysql_query("SELECT count(*) FROM profits WHERE usernamefield='$safe_id'") or die(mysql_error();
$row = mysql_fetch_array($result);
$count = $row[0];

is how things should look.

Upvotes: 1

Jage
Jage

Reputation: 8096

    $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($user_nameid) FROM profits");

   $total = reset(mysql_fetch_assoc($result));

//comment this next line if you don't want to output to the browser
    echo $total; 

      mysql_close($con);

Upvotes: 1

Tom van der Woerdt
Tom van der Woerdt

Reputation: 29985

You could use mysql_result

$sum = mysql_result($result, 0);

Upvotes: 1

Related Questions