【问题标题】:Having Trouble Getting a MySQL Query Result into a PHP Array无法将 MySQL 查询结果输入 PHP 数组
【发布时间】:2015-07-28 18:34:18
【问题描述】:

我正在尝试将 mysql 查询结果放入 PHP 数组。当我运行脚本并打印数组时,它不会显示从 mysql 表中获取的信息,而只是显示有关数组的信息。

这是我的代码:

<?php
class db {
  public $conn;
  function dbLogin() {
    $this->conn = new mysqli("1.2.4.3","user","pwd","database");    
  }

  public function selectQuery() {
    $this->dbLogin();
    $query = "
        SELECT      *
        FROM        myTable
    ";
    echo "<pre>";
    $resultArray = Array();
    if ($result = $this->conn->query($query)) {
        while ($row = $result->fetch_array()) {
            $resultArray[] = $result;
        }

    }
    var_dump($resultArray);
    echo "</pre>";
  }
}

$fData = new db();
$fData->selectQuery();
?>

当我运行上面的脚本时,我得到了这个:

array(88) {
[0]=>
object(mysqli_result)#3 (5) {
["current_field"]=>
int(0)
["field_count"]=>
int(34)
["lengths"]=>
NULL
["num_rows"]=>
int(88)
["type"]=>
int(0)
}
[1]=>
object(mysqli_result)#3 (5) {
["current_field"]=>
int(0)
["field_count"]=>
int(34)
["lengths"]=>
NULL
["num_rows"]=>
int(88)
["type"]=>
int(0)
}
...
}

以上是页面上显示的显示/对象/数组的 88 个实例中的前两个。但它不显示来自数据库的实际信息。

到目前为止我已经尝试过:

我尝试了echovar_dumpprint_rprintf 数组,但没有成功。我真的很想在数组中看到查询结果,所以我知道我的脚本正在按照我想要的方式工作,但我似乎不知道该怎么做。

我知道该查询可以正常工作,并且如果我将 $resultArray[] = $result; 替换为 echo $result[0] . $result[1] (etc...),我可以从该表中看到结果。

如何从查询中查看数组中的数据,以便知道我的脚本正在运行?

【问题讨论】:

  • $result 是您的查询。尝试转储$row

标签: php mysql arrays var-dump


【解决方案1】:

$resultArray[] = $result; 更改为$resultArray[] = $row;

【讨论】:

  • 我的愚蠢疏忽。这做到了。谢谢!
【解决方案2】:

添加到 someOne 的解决方案中,var_dump() 确实除了组件名称外,还为您提供了数组的值。数据类型后括号中的数字或字符串是数组的值:

array(88) {
[0]=>
object(mysqli_result)#3 (5) {
["current_field"]=>
int(0)
["field_count"]=>
int(34)
["lengths"]=>
NULL
["num_rows"]=>
int(88)
["type"]=>
int(0)
}

这里,字段current_field 的类型为int,值为0num_rows 也有 int 类型和值 88 等。

【讨论】:

    【解决方案3】:

    请更改代码

    if ($result = $this->conn->query($query)) {
        while ($row = $result->fetch_array()) {
            $resultArray[] = $result;// this would be $row
        }
    
    }
    

    if ($result = $this->conn->query($query)) {
        while ($row = $result->fetch_array()) {
            $resultArray[] = $row;
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2012-08-26
      • 2012-02-16
      • 2015-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-17
      • 2014-01-08
      相关资源
      最近更新 更多