需要将结果作为PHP变量保存在MySQL SUM()查询的结果之外

时间:2012-04-23 17:51:38

标签: php mysql sum echo

我需要回显MySQL查询的结果,查询有效。只需完成如何弄清楚如何回应它的结果。

 $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);

提前致谢,非常感谢所有帮助!

3 个答案:

答案 0 :(得分:1)

您可以使用mysql_result

$sum = mysql_result($result, 0);

答案 1 :(得分:1)

    $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);

答案 2 :(得分:1)

不确定您对查询的看法。 SUM()适用于您查询的表中的特定FIELD。很可能你想要

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

注意变量周围的引号。如果该变量包含非纯数字的任何内容,则必须引用该变量。而且你还必须处理任何SQL注入问题:

$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];

是应该看的样子。