【问题标题】:Why do I get "Resource id #4" when I apply print_r() to an array in PHP? [duplicate]当我将 print_r() 应用于 PHP 中的数组时,为什么会得到“资源 id #4”? [复制]
【发布时间】:2010-12-19 03:59:53
【问题描述】:

可能重复:
How do i “echo” a “Resource id #6” from a MySql response in PHP?

下面是代码:

$result=mysql_query("select * from choices where a_id='$taskid'")or die(mysql_error());
print_r($result);

我得到“资源 id #4”,你知道吗?

我添加后

while($row=mysql_fetch_assoc($result))
{ print_r($row); }

我刚收到[]

怎么了?

【问题讨论】:

  • print_r 将只接受数组和对象。如果你使用 var_dump() 它会给你任何你给它的信息。

标签: php mysql arrays


【解决方案1】:

Resources 是 PHP 用来跟踪外部资源(如数据库连接、文件句柄、套接字等)的特殊变量类型。

【讨论】:

    【解决方案2】:

    您正在尝试打印 mysql resource variable 而不是它引用的资源中包含的值。您必须首先尝试使用mysql_fetch_assoc() 等函数提取您获得的值。

    您也可以尝试mysql_fetch_array() 或mysql_fetch_row(),但我发现关联数组非常好,因为它们允许您通过字段名称访问它们的值,如Mike's example。

    【讨论】:

      【解决方案3】:

      $result 是mysql_query 返回的资源变量。更多关于资源变量:http://php.net/manual/en/language.types.resource.php

      您必须使用mysql_fetch_array()或mysql_fetch_assoc()等其他函数来获取查询结果集的数组。

      $resultset = array();
      $result=mysql_query("select * from choices where a_id='$taskid'") or die(mysql_error());
      while($row = mysql_fetch_assoc($result)){
        $resultset[] = $row; // fetch each row...
      }
      mysql_free_result($result); // optional though...
      
      print_r($resultset);
      

      见:

      http://php.net/manual/en/function.mysql-fetch-array.php
      http://php.net/manual/en/function.mysql-fetch-assoc.php
      http://php.net/manual/en/function.mysql-query.php

      【讨论】:

        【解决方案4】:

        mysql_query() 不会将数组返回为explained in the manual。将mysql_fetch_array()、mysql_fetch_assoc() 或mysql_fetch_row() 与$result 一起使用。有关如何操作查询结果的更多信息,请参阅上面的链接。

        $result = mysql_query('SELECT * FROM table');
        while ($row = mysql_fetch_assoc($result)) {
            echo $row["userid"];
            echo $row["fullname"];
            echo $row["userstatus"];
        }
        

        【讨论】:

          猜你喜欢
          • 2010-12-19
          • 2020-10-02
          • 1970-01-01
          • 2011-06-15
          • 2015-01-31
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多