如何回显查询

时间:2013-02-02 06:32:07

标签: php mysql

  

可能重复:
  Why does this return Resource id #2?

我希望回显mysql_query("SELECT SUM(onlineplayers) FROM servers")但是当我在前面放置echo时,它会显示资源ID#2,当我在末尾添加or die(mysql_error());时,它只输出1。

4 个答案:

答案 0 :(得分:2)

您需要先获取查询:

$result = mysql_query("SELECT SUM(onlineplayers) FROM servers");
if($result){
  $data = mysql_fetch_assoc($result);
  echo $data[0];
}

但是,除非绝对必要,否则不应使用mysql_函数。用于新项目的mysql扩展名is NOT recommended。相反,你应该使用PDO_mysql或mysqli

来源: Why does this return Resource id #2?

答案 1 :(得分:1)

使用以下代码

$str = "SELECT SUM(onlineplayers) FROM servers";  //this will set the query in string format
echo $str;    // this will echo the query;
mysql_query($str);   // this will run the query

答案 2 :(得分:1)

$q = mysql_query("SELECT SUM(onlineplayers) as `total` FROM servers"); // notice the "as `total`
$r = mysql_fetch_array($q); // will return the result
echo $r['total']; // will echo the count

在旁注中,请停止使用mysql_*个功能。更多信息here

答案 3 :(得分:0)

$str = "SELECT SUM(onlineplayers) FROM servers"; 
echo $str; 
$result = mysql_query($str); 
$row= mysql_fetch_array($result);
print_r($row);