【问题标题】:How to echo a query [duplicate]如何回显查询[重复]
【发布时间】:2013-02-02 06:32:07
【问题描述】:

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

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

【问题讨论】:

  • 什么? 当我将 echo 放在前面时是什么意思?
  • mysql_query() 的返回类型不是您查询的字符串结果,而是resource(至少在您的情况下)。 Read the docs.
  • mysql_query() 执行查询并返回输出,因此您得到的输出具有资源 #2。要输出查询,您需要将查询分配给变量并回显变量并将其传递给 mysql_query 函数
  • 1) Yogesh Suthar 是正确的。要回显您的查询字符串,请将其放入变量中并回显该变量。 2)你真的应该使用 mysqli 或 PDO 而不是(旧的,已弃用的)“mysql_query()”API。 3)您还应该尽可能使用准备好的语句。 最重要的 - 4) 你不能只是“回显查询的结果”。您需要调用 API 来获取结果。然后你可以显示你获取的内容:)

标签: php mysql


【解决方案1】:

您需要先获取查询:

$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?

【讨论】:

    【解决方案2】:

    使用下面的代码

    $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
    

    【讨论】:

    • 对不起,我可能没有解释得太清楚。我想回显mysql_query("SELECT SUM(onlineplayers) FROM servers"); 的输出
    • @Enigmo 如果您想查看查询的输出,那么它将显示Resource Id #2 this。
    • @Enigmo 如果您想查看查询结果,请使用此函数mysql_fetch_*
    【解决方案3】:
    $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

    【讨论】:

      【解决方案4】:
      $str = "SELECT SUM(onlineplayers) FROM servers"; 
      echo $str; 
      $result = mysql_query($str); 
      $row= mysql_fetch_array($result);
      print_r($row);
      

      【讨论】:

        猜你喜欢
        • 2013-07-10
        • 1970-01-01
        • 2016-05-08
        • 1970-01-01
        • 2013-04-10
        • 1970-01-01
        • 2013-06-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多